package com.example.beidouapplication;

import static java.lang.Math.floor;

import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.beidouapplication.viewmodel.Key;
import com.example.beidouapplication.viewmodel.KeyEvent;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

//
public class Menu {
    public static final String NS_DATA_UNUSED_MSG = "卫星定位数据无效，请返回";
    public static final Key TAB = Key.Tab;
    private static final boolean STOP = false;
    //    public static  CountDownTimer COUNT_DOWN_TIMER;
    //
    volatile static ArrayBlockingQueue<KeyEvent> keyQueue = new ArrayBlockingQueue<>(10);
    //    /*键值*/
//    volatile static int Esc = 0x1b;
    volatile static int Tab = 0x09;
    //    volatile static int Enter = 0x0d;
    final static Key Enter = Key.ENTER;
    final static Key Esc = Key.Esc;


    volatile static int Del = 0x53;
    volatile static int Left = 0x4b;
    volatile static int Right = 0x4d;
    volatile static int Up = 0x48;
    volatile static int Down = 0x50;
    volatile static int PgUp = 0x49;
    volatile static int PgDn = 0x51;
    /*模拟键值*/
    volatile static int KeyQD = 0x40;                                            /*启动qidong	 F6*/
    volatile static int KeyDH = 0x3b;                                            /*导航daohang	 F1*/
    volatile static int KeyXB = 0x3d;                                            /*寻北xunbei	 F3*/
    volatile static int KeyCP = 0x3f;                                            /*测漂biaoding F5*/
    volatile static int KeyXT = 0x3e;                                            /*系统xitong	 F4*/
    /*界面名称和编号*/
    public static final int LOGO = 0;                    /*6z3A-17定位导航系统*/
    public static final int MENU_START = 1;                    /*启动界面，显示启动方式*/
    public static final int MENU_START_S1 = 2;                    /*选择启动方式,通过y决定ini_model值*/
    public static final int START_NM = 3;                    /*显示初始坐标选择（手动或卫星）*/
    public static final int START_NM_S1 = 4;                    /*选择初始坐标来源*/
    public static final int I_C_CONF = 9;                    /*输入坐标确认*/
    public static final int I_C_CONF_S1 = 10;                /*输入坐标确认*/
    public static final int POST = 11;                /*系统自检请等待*/
    public static final int POST_S1 = 12;                /*根据postR,计算判断检测界面的内容*/
    final static int INI_CAL_POST_OK = 13;                /*自检正常,	系统初始化*/
    final static int INI_CAL_S1 = 15;                /*系统初始化，请等待*/
    final static int DRIFT_CAL_PRE = 20;                /*测漂菜单*/
    final static int DRIFT_CAL = 21;                /*测漂*/
    final static int ALIGN_PRE = 22;                /*寻北准备界面*/
    final static int ALIGN = 23;                /*选择坐标输入方式界面*/
    final static int CALIBRATION_PRE = 24;                /*标定起点坐标*/
    final static int CALIBRATION_S1 = 26;                /*标定开始，按PgDn结束*/
    final static int CALIBRATION_S2 = 27;                /*按PgDn后输入进入下一页*/
    final static int CALIBRATION_S3 = 28;                /*标定终点坐标输入*/
    final static int CALIBRATION_S4 = 29;                /*标定终点坐标确认*/
    final static int CALIBRATION_S5 = 30;                /*标定参数显示或失败界面*/
    final static int CALIBRATION_S6 = 31;                /*按Esc键返回标定界面*/
    final static int CALIBRATION_S6_PRE = 32;                /*按Esc键返回标定界面*/
    final static int WIN_NAV_P1_PRE = 33;                /*惯性导航界面*/
    final static int WIN_NAV_P1 = 34;                /*惯性导航界面*/
    final static int WIN_NAV_P2_PRE = 35;                /*卫星导航界面*/
    final static int WIN_NAV_P2 = 36;                /*卫星导航界面*/
    final static int ALIGN_COR_NEW_PRE = 41;                /*输入寻北用新坐标*/
    final static int ALIGN_COR_NEW = 42;                /*输入寻北用新坐标*/
    final static int ALIGN_S1_PRE = 43;                /*寻北坐标确认*/
    final static int ALIGN_S1 = 44;                /*寻北坐标确认*/
    final static int ALIGN_COR_NEW_CONF_PRE = 45;                /*正在寻北禁动设备*/
    final static int ALIGN_COR_NEW_CONF = 46;                /*正在寻北禁动设备*/
    final static int PARA_SET_PRE = 47;                /*安装误差和里程系数*/
    final static int PARA_SET_S1 = 48;                /*输入*/
    final static int PARA_SET_S2 = 49;                /*确认输入*/
    final static int PARA_SET_S3 = 50;                /*传输给方位保持仪*/
    public static final int MENU_MAIN = 51;                /*主菜单*/
    public static final int MENU_MAIN_S1 = 52;                /*主菜单选择*/
    public static final int MENU_INI = 53;                /*系统菜单界面*/
    public static final int MENU_INI_S1 = 54;                /*系统菜单界面选择*/
    public static final int GetBDInfo_PRE = 63;                /*北斗状态查询*/
    static final int GetBDInfo_S1 = 64;                /*北斗状态查询显示*/
    static final int SetFix_PRE = 65;                /*参考点数据设定*/
    static final int SetFix_S1 = 66;                //参考点坐标输入
    static final int SetFix_S2 = 67;                /*参考点坐标输入显示*/
    static final int SetFix_S3 = 68;                /*参考点坐标输入确认*/
    static final int SetFix_S4 = 69;                /*参考点坐标确认后向方位保持仪发送新坐标*/
    static final int SelfTest_PRE = 72;                /*系统定位定向装置自检结果*/
    static final int SelfTest_S1 = 73;                /*系统定位定向装置自检寻出*/
    static final int SelfTest_S2 = 74;                /*测漂计算确认*/
    static final int DRIFT_CAL_CONF = 77;                /*测漂确认*/
    static final int SysParaInfo_PRE = 78;                /*输入密码*/
    static final int SysParaInfo_S1 = 79;                /*判断密码*/
    static final int SysParaInfo_S2 = 80;                /*输入安装误差*/
    static final int SysParaInfo_S3 = 81;                /*确认安装误差*/
    static final int GetMntErr_PRE = 82;                /*选择导航参数和安装误差*/
    static final int GetMntErr_S1 = 83;                /*选择导航参数和安装误差*/
    static final int CALIBRATION_CER_PRE = 88;                /*导航参数标定准备（输入密码）*/
    static final int CALIBRATION_CER = 89;                /*导航参数输入*/
    static final int NS_DATA_UNUSED = 90;                /*卫星定位数据无效，按任意键返回*/
    static final int NS_DATA_UNUSED_S1 = 91;                /*计算按任意键后返回的界面*/
    static final int FIX_FORMAT_SEL = 92;                /*显示平面坐标或大地坐标选项*/
    static final int FIX_FORMAT_SEL_S1 = 93;                /*选择平面坐标或大地坐标*/
    static final int START_NM_NewFix = 94;                /*手动输入初始坐标*/
    static final int START_NM_NewFix_S1 = 95;                /*手动输入初始坐标*/
    static final int NorthFinderFault_PRE = 96;                /*寻北失败数据无效*/
    static final int NorthFinderFault_S1 = 97;                /*寻北失败数据无效,按Esc键返回导航界面*/
    static final int COR_INPUT_ERROR = 98;                //坐标输入错误,
    static final int Beidou_self_destroy_P1 = 101;                /*北斗自毁*/
    static final int Beidou_self_destroy_P2 = 102;
    static final int Beidou_self_destroy_P3 = 103;
    static final int Beidou_self_destroy_P4 = 104;
    static final int Beidou_self_destroy_P5 = 105;
    static final int Beidou_self_destroy_P6 = 106;
    static final int Beidou_self_destroy_S1 = 107;
    static final int Beidou_self_destroy_S2 = 108;
    static final int Beidou_self_destroy_S3 = 109;
    static final int Beidou_self_destroy_S4 = 110;


    volatile static ArrayList<Integer> noBackStage = new ArrayList<>();

    static {
//        noBackStage.add(LOGO);
        noBackStage.add(DRIFT_CAL);
        noBackStage.add(INI_CAL_S1);
        noBackStage.add(ALIGN_S1);
    }



    //    static final String password = "68912543";
    static final String password = "0";
    //
    volatile static int FixGaussPlane = 0x00;
    volatile static int FixGeoOrth = 0x02;
    //    /*********************************************/
//
//    /*********************************************/
    static BeidouTime BeiDouTime = new BeidouTime();
    static BeidouTime RDSS_BeiDouTime = new BeidouTime();
    //
    static double M_PI = Math.PI;

//
    static class PMU_data {
        byte[] FP = new byte[2];
        byte[] year = new byte[3];
        byte[] month = new byte[3];
        byte[] day = new byte[3];

    }

    static PMU_data PMU_data_From = new PMU_data();
    static PMU_data PMU_data_To = new PMU_data();

    //
    static class ICM_data {
        byte[] year = new byte[3];
        byte[] month = new byte[3];
        byte[] day = new byte[3];

    }

    //
    static ICM_data ICM_data_To = new ICM_data();

    //
//
    static class YYYYMMDD_data {
        byte[] year = new byte[5];
        byte[] month = new byte[3];
        byte[] day = new byte[3];

    }

    static YYYYMMDD_data BDZH_data = new YYYYMMDD_data();
    //
//
//    static int c54bits = 9;
    static int Time_Init = 15;                                                    /*正常启动时间15分钟*/
    static int Time_DriftCal = 5;                                            /*测漂时间5分钟*/
    static int Time_NorthFinder = 5;                                        /*寻北时间*/
    static final int INI_NM = 0x01;                                                    /*惯性导航正常启动方式,15分钟*/
    static final int INI_EX = 0x02;                                                    /*惯性导航快速启动方式,	5分钟*/
    //
    static MyPointer<Double> DDrLat54 = new MyPointer<>(0.0);
    static MyPointer<Double> DDrLong54 = new MyPointer<>(0.0);
    static MyPointer<Double> DDrX54 = new MyPointer<>(0.0);
    static MyPointer<Double> DDrY54 = new MyPointer<>(0.0);
    static MyPointer<Double> DConvergence54 = new MyPointer<>(0.0);/*54坐标系参数，不一定是54了。*/
    static volatile int timeFlag = 0;                                            //总是从变量的内存处读取数据
    static volatile long countFlag = 0;                                            //总是从变量的内存处读取数据
    static volatile int lotusFlag = 0;                                            //总是从变量的内存处读取数据
    //    static int tim;                                                                        /*tim记录中断次数,大于7年的记录时间量*/
//
    static long start = tim();
    static long end;
    static int tim_twin_a;
    static int tim_twin_b;
    static int tim_twin_c;

    static long tim_token = tim();                                                        /*每10秒查询寻北仪状态和定位定向装置启动状态*/
    static boolean choke;                                                                    /*往通信处理机发送数据时置高,防止数据更新时错帧*/
    //
//
    static COM1_Buf Buf_Com1 = new COM1_Buf(4096);                                                /*外部变量，可被其它文件引用，定义串口1类的对象*/
    //    //    COM2_Buf Buf_Com2(512);													/*外部变量，可被其它文件引用，定义串口2类的对象*/
    static COM3_Buf Buf_Com3 = new COM3_Buf(1024);                                                /*外部变量，可被其它文件引用，定义串口3类的对象*/
    static COM4_Buf Buf_Com4 = new COM4_Buf(4096);                                                /*外部变量，可被其它文件引用，定义串口4类的对象*/

    static COM1_Buf COM1 = Buf_Com1;
    static COM3_Buf COM3 = Buf_Com3;
    static COM4_Buf COM4 = Buf_Com4;
    static byte[] buf = new byte[18];
    static byte[] bc_data = new byte[36];                                                /*串口缓冲器地址*/
    static byte[] zc_data = new byte[512];
    //    char[] bd_data = new char[512];
    static byte[] obuf = new byte[18];                                            /*串口1,3输出缓冲器*/
    //
//
    static CCoordTrans rover = new CCoordTrans();
    //
    static int iBelt = 20;                                                                //默认为北京地区分度带
    //    int ChDeg[2]=
//
//    {
//        248, 0x0
//    },ChMin[2]=
//
//    {
//        39, 0x0
//    },ChSec[2]=
//
//    {
//        34, 0x0
//    }
//
//    ;                                //度,分,秒的数学符号
//
    static int checksum = 0;
    static int checksum_H = 0;
    static int checksum_L = 0;
    //    *po;
//    int len = 0;
    static double BdLatitude = 0;                                                        //直接从北斗串口收到的纬度值,单位度
    static double BdLongitude = 0;                                                        //直接从北斗串口收到的经度值,单位度
    static int BdLatitude_Dir = 0;
    static int BdLongitude_Dir = 0;
    static int BdHeight = 0, BdVarHeight = 0;
    static int BdX = 0, BdY = 0;                                                                    //经转换后的北斗平面直角坐标值_长整型
    private static MyPointer<Double> BdX_double = new MyPointer<>(0.0);
    private static MyPointer<Double> BdY_double = new MyPointer<>(0.0);
    private static MyPointer<Integer> RDSS_BdX = new MyPointer<>(0);
    private static MyPointer<Integer> RDSS_BdY = new MyPointer<>(0);
    static int Num_DWR = 0;                                                                        //RDSS定位次数
    static double RDSS_BdLatitude = 0;                                                        //直接从北斗串口收到的RDSS纬度值,单位度
    static double RDSS_BdLongitude = 0;                                                    //直接从北斗串口收到的RDSS经度值,单位度
    static int RDSS_BdLatitude_Dir = 0;
    static int RDSS_BdLongitude_Dir = 0;
    static int RDSS_BdHeight;
    static int RDSS_BdVarHeight;
    //    int RDSS_BdX, RDSS_BdY;                                                                    //经转换后的北斗平面直角坐标值_长整型
//
//    FILE *fp,*fp_BDZH;
//    /*指向FILE类型结构体类型的指针变量*/
    static boolean fgTempCtrlAlarm = false;
    static long cntTempCtrlAlarm = 0;
    //    /*******************************************************/
    double dFuseX = 0;
    double dFuseY = 0;
    static double dDeltD = 0;
    static double dStoredD = 0;
    double dFuseK = 0.15;
    //    int cntIntegratingOp = 0;
//    /*******************************************************/
    static long ux1, uy1, ud;                                    //从方位保持传来的导航数据,显示在惯导界面上,传给上位机的惯性数.
    static short uh1;                                //方为保持仪输出的高程计相对高度
    static int lar = 0;
    static float la;                                    //航向角,mil
    static float mountErr = 0;                        /*读取存贮在文件中的安装误差*/
    static long dx, dy;                            //给方位保持的X,Y值,输入的平面坐标
    static short lh, lhr;                            //给方位保持的H值,lhr是lh经过判断正负值后的结果.
    static int ini_mode = 0x01;                                                        /*0x01:正常启动；0x02:快速启动*/
    static byte[][] BDchBox = new byte[32][32];
    static char BDchRow;
    static char BDchFile;
    //
    static int GGA_Data_Status = 0x0;                                            //GGA卫星数据状态指示,0-8,0表示定位模式不可用或无效
    static int INS_Ini = 0;                                                                /*定位定向系统启动*/
    static boolean postR;                                                                    /*上电自检结束*/
    //
//    static int stage = MENU_MAIN;                                                                                    /*界面编号*/
    static int stage = LOGO;                                                                                    /*界面编号*/
    static int HostStage = 0x0;
    volatile static boolean initG = true;                                                                    /*方位保持已启动*/
    static int ErrCodeFromBC = 0xffff;                                        /*方位保持仪传输来的检测代码*/
    static int ErrCode = 0x00;                                                            /*给通信处理机的故障码,0：正常，1：故障*/
    static int BD_Status = 0x0;                                                        //北斗故障状态.
    static double HDOP;
    static double VDOP;
    static int Num_Statelite = 0x0;                                                //可视卫星数
    static double k, mntErr;                                                            /*里程系数,安装误差*/

    static int FixFormat = 0x00;

    //
    static double dB, dL, dH;

    static MyPointer<Double> X54 = new MyPointer<>(0.0), Y54 = new MyPointer<>(0.0);                                                /*输入的地里坐标*/

    /**
     * if (tTimeR > 1e-10)  tTimeR = tTimeT - ((tim - start) / 18.2)
     * tTimeR是剩余时间，tTimeT是开始时间，tim是定时器自增，大约1s增加18.2次？
     */
//    static double tTimeR, tTimeT;                                                    /*倒计时,设定时间*/
    static long tTimeR, tTimeT;                                                    /*倒计时,设定时间*/

//if (tTimeR > 1e-10) {
//        tTimeR = tTimeT - ((tim - start) / 18.2);


    static int norFT, testDT, calOk;
//
//    /*********************************************/

    static long tim() {
        return System.currentTimeMillis();
    }

    static Timer timer = new Timer();

//    static {
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                timeFlag++;
//            }
//        }, 1000);
//    }

    static boolean NF_OnRun;                                                                /*寻北仪正寻北*/
    static byte FKI_ZHS = 0;                                                                                                                                                                                    //北斗自毁命令执行状态反馈
    static int id_stat = 0;                                                                /*判断方位保持仪是否复位标识*/


    static long RCV_FRM_BD_tim = 0;                                                //收到北斗串口数据内部时刻
    static long RCV_FRM_BDGGA_tim = 0;                                        //收到北斗串口GGA数据的内部时刻

    static boolean firstInit = false;

    static String toZC_DATA = "";
    static int Len_toZC_DATA = 0;
    static byte[] bd_data_x = new byte[300];
    static int cn = 0;                                                                            /*收到的串口字节数*/
    static double velocity = 0.0, pitch = 0.0, roll = 0.0;

    static byte[] PMU_OPEN = new byte[]{'$', 'C', 'C', 'R', 'M', 'O', ',', 'P', 'M', 'U', ',', '2', ',', '1', '*', 'F', 'F', 0x0D, 0x0A};            //PMU查询指令,CCRMO的和校验感觉都是FF
    static byte[] ICM_OPEN = new byte[]{'$', 'C', 'C', 'R', 'M', 'O', ',', 'I', 'C', 'M', ',', '2', ',', '1', '*', 'F', 'F', 0x0D, 0x0A};            //ICM查询命令，CCRMO的和校验感觉都是FF
    static byte[] PMU_CLOSE = new byte[]{'$', 'C', 'C', 'R', 'M', 'O', ',', 'P', 'M', 'U', ',', '1', ',', '1', '0', '*', 'F', 'F', 0x0D, 0x0A};            //PMU关闭指令,CCRMO的和校验感觉都是FF
    static byte[] ICM_CLOSE = new byte[]{'$', 'C', 'C', 'R', 'M', 'O', ',', 'I', 'C', 'M', ',', '1', ',', '1', '0', '*', 'F', 'F', 0x0D, 0x0A};

    static byte[] ZHS = new byte[]{'$', 'C', 'C', 'Z', 'H', 'S', ',', 'A', 'A', '5', '5', '5', '5', 'A', 'A', '*', '6', 'D', 0x0D, 0x0A};                //北斗自毁命令

    static int idReady = 0;                                                                /*与方位保持仪建链标志*/

    static {
        PMU_data_From.FP[0] = '0';
        PMU_data_From.FP[1] = '\0';
        PMU_data_From.year[0] = '0';
        PMU_data_From.year[1] = '0';
        PMU_data_From.year[2] = '\0';
        PMU_data_From.month[0] = '0';
        PMU_data_From.month[1] = '0';
        PMU_data_From.month[2] = '\0';
        PMU_data_From.day[0] = '0';
        PMU_data_From.day[1] = '0';
        PMU_data_From.day[2] = '\0';

        PMU_data_To.FP[0] = '0';
        PMU_data_To.FP[1] = '\0';
        PMU_data_To.year[0] = '0';
        PMU_data_To.year[1] = '0';
        PMU_data_To.year[2] = '\0';
        PMU_data_To.month[0] = '0';
        PMU_data_To.month[1] = '0';
        PMU_data_To.month[2] = '\0';
        PMU_data_To.day[0] = '0';
        PMU_data_To.day[1] = '0';
        PMU_data_To.day[2] = '\0';

        ICM_data_To.year[0] = '0';
        ICM_data_To.year[1] = '0';
        ICM_data_To.year[2] = '\0';
        ICM_data_To.month[0] = '0';
        ICM_data_To.month[1] = '0';
        ICM_data_To.month[2] = '\0';
        ICM_data_To.day[0] = '0';
        ICM_data_To.day[1] = '0';
        ICM_data_To.day[2] = '\0';

        BDZH_data.year[0] = '1';
        BDZH_data.year[1] = '9';
        BDZH_data.year[2] = '8';
        BDZH_data.year[3] = '0';
        BDZH_data.year[4] = '\0';
        BDZH_data.month[0] = '1';
        BDZH_data.month[1] = '2';
        BDZH_data.month[2] = '\0';
        BDZH_data.day[0] = '3';
        BDZH_data.day[1] = '0';
        BDZH_data.day[2] = '\0';
    }

    static void main() {
//        int color;                                                                                    /*可能不需要定义*/
////        int key1, key2 = 0;                                                                        /*分别记录键盘扫描码的低字节或高字节*/
//        int left, top, right, bottom;                                                    /*信息窗的坐标*/
//        int x, y, tab = 0;                                                                            /*当前光标位置*/
//        int[] xoffset = new int[3], dots_num = new int[3];                    /*计算光标位置*/
////        int item = 0;                                                                                    /*子项目号*/
//        int size;                                                                                        /*the	numbert	of butes required	to store a bit image*/
////        void *buffer;
//        int ch;
//        int[] s = new int[2] {
//            '0', '\0'
//        },data_buf = new int[3][c54bits + 1];                /*ch=key1,应该合并*/
//        int[] num_bits = new int[]{c54bits, c54bits, 5};
//        int[] num_bits2 = new int[]{6, 6};
//        int l, t, r, b;
//        l = 0;
//        t = 0;
//        r = 10;
//        b = t + 17;
//        int uLM = 0, uTM = 0;
//        char[] cuxyz = new char[20];
//        int count = 0;
//        double iPart;                                                                                    /*可能是分度带的意思*/
//        int fore_color;                                                                                    /*用于记录先前视场颜色*/
//        textsettingstype texttype;                                                            /*定义结构体变量,font;direction;charsize;horiz;vert*/
////        fillsettingstype filltype;															/*定义结构体变量,left;right;top;bottom;clip*/
////        viewporttype		 viewtype,viewtype_pre;									/*定义结构体变量,fill	paten;fill color*/
//        int backdoor;
//        int BitXor;                                                                        /*校验和*/
//
////	static	int	ErrBC=0x63FF;											/*方位保持仪*/
////	static	int	ErrXB=0x64FF;											/*寻北仪*/
////	static	int	ErrGC=0x61FF;											/*高程计*/
////	static	int	ErrDX=0x65FF;											/*导航显示器*/
//
//        int MAXX = 320;
//        int MAXY = 256;
//        int OWndX = 160;
//        int OWndY = 80;
//        int menu_item_max = 5;
//        int menu_item = 0;
//        int submenu_item = 0, submenu_item_max = 3;
//        int pwd;
        if (!firstInit) {

            firstInit = true;
            //车速度、俯仰角、横滚角，由于安装关系，与寻北仪相应角交叉
//
///***************2016-11-20********************/

//
//
            //ICM关闭命令,CCRMO的和校验感觉都是FF
////******************************************************
            initSys();                                            /*调用系统初始化模块*/
//        ccc.Initialize();
//        che.openhzk('s');
//        cleardevice();
//        highvideo();
//        outtextxy(MAXX / 2 - 83, MAXY / 2 - 18, "88888888");
//        settextstyle(textinfo.font, textinfo.direction, textinfo.charsize);
//        che.puthz16(MAXX / 2, MAXY / 2 - 15, 2, WHITE, "888888系统");
//
//        stage = LOGO;
//        while (backdoor != 0x64) {
        }

        timeFlag += 1;
        switch (stage) {                                                                /*按Tab键进入到主菜单界面*/    /*bioskey(1):tests if	a	keystroke	is aviable to	read*/


            case LOGO:
//                    // logo，没用
                    if(bioskey1())
                    {
//                        key1=bioskey(0)&0xff;									 /*bioskey(0):returns	the	actual keystroke*/
//                        if(key1==0x09)
//                        {
//                            cleardevice();												/*内置函数,eraces	the	entire the graphic screen	and	moves	the	CP(current position) to	(0,0)*/
//                            ShowMain();													/*主菜单界面*/
//                        }
//                        else	if(key1==Esc)
//                        {
//                            ;
//                        }
                        KeyEvent key = bioskey0();
                        if (key.type == Key.Esc) {
                            stage=MENU_MAIN;

                        }
                    }
//
//                    // 好像也没用
                     if(idReady > 0)													/*与方位保持仪建链*/
                    {
//                        cleardevice();
//                        ShowMain();
                        stage=MENU_MAIN;
                    }
//
//                    // 定时器定时往com3发数据？
                    if (timeFlag > 0)                                                     /*系统定时器中断*/ {
//                        timeFlag = 0;
                        if ((timeFlag % 18) == 0)                                         /*循环18次,约一秒间隔时收方位保持仪数据*/ {
                            buf[0] = (byte) 0xf1;
                            Buf_Com3.PutData(buf, 8);
                        }
                    }
//                stage = MENU_MAIN;
                changeStageUI(FragmentLogo.instance);

                    break;
//
            case MENU_MAIN:                                                                                                    /*主菜单界面*/
//                    // 好像没什么用
////                    Clr_scr();																									/*清除菜单和状态栏外的视场并设定最大视场*/
////                    setviewport(0,0,319,256,1);																	/*Clr_scr有同样功能,可省略*/
////                    fore_color=getcolor();
////                    setcolor(BLACK);
////                    size=imagesize(8,2,60,19);																	/*the	numbert	of butes required	to store a bit image*/
////                    buffer=new int[size];																			/*set	a	new	memory to	store	a	bir	image*/
////                    getimage(8+menu_item*60,2,60+menu_item*60,19,buffer);
////                    putimage(8+menu_item*60,2,buffer,NOT_PUT);									/*位图颜色取反*/		 /*output	a	bit	image	onto the screen*/
//                MainActivity.fragmentManager.beginTransaction().hide(new Fragment());
                MainActivity.instance.clearSelection();
                changeStageUI(new Fragment());
                stage = MENU_MAIN_S1;
///***
// * 这里是控制主菜单的，stage的跳转在MainActivity里做
// */
            case MENU_MAIN_S1:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();
                    if (key.type == Key.ENTER) {
                        switch (key.menu_item) {
                            case 0:                                                                        /*启动菜单*/
                                if (!initG)                                                            /*如果方位保持仪还没启动,initG==0*/ {
                                    stage = MENU_START;
                                } else {
                                    stage = MENU_MAIN;                                        /*如果已启动,则恢复到主菜单界面*/
                                }
                                break;
                            case 1:                                                                    /*导航菜单*/
                                stage = WIN_NAV_P1_PRE;
                                break;
                            case 2:                                                                    /*寻北菜单*/
                                stage = ALIGN_PRE;
                                break;
                            case 3:                                                                    /*测漂菜单*/
                                if (initG)                                                            /*方位保持已启动*/ {
                                    stage = DRIFT_CAL_PRE;                                //测漂菜单
                                } else                                                                    /*方位保持未启动,转到主程序界面*/ {
                                    stage = MENU_MAIN;
                                }
                                break;
                            case 4:                                                                    /*系统菜单*/
                                stage = MENU_INI;
                                break;
                            default:
                                break;
                        }
                    } else {
                        ;
                    }
                }
                break;
//
            case MENU_INI:
//                    outtextxy(30,15,"1.");
//                    che.puthz16(50,20,2,WHITE,"定位导航系统自检");
//                    outtextxy(30,35,"2.");
//                    che.puthz16(50,40,2,WHITE,"卫星定位系统查询");
//                    outtextxy(30,55,"3.");
//                    che.puthz16(50,60,2,WHITE,"参考点坐标设定");
//                    outtextxy(30,75,"4.");
//                    che.puthz16(50,80,2,WHITE,"导航参数标定");
//                    outtextxy(30,95,"5.");
//                    che.puthz16(50,100,2,WHITE,"系统参数设置及查询");
//                    outtextxy(30,115,"6.");
//                    che.puthz16(50,120,2,WHITE,"北斗自毁");
//
                MainActivity.instance.setRed(4);
                changeStageUI(FragmentMenuIni.instance);
                stage = MENU_INI_S1;
//
            case MENU_INI_S1:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();
                    if (key.type == Key.Esc)                                    /*按ＥSc键转到主菜单界面*/ {
                        stage = MENU_MAIN;
                    }
                    if (key.type == Key.ENTER) {
                        switch (key.menu_item) {
                            case 1:
                                stage = SelfTest_PRE;                    /*自检*/
                                break;
                            case 2:
                                stage = GetBDInfo_PRE;
                                break;
                            case 3:
                                if (initG) {
                                    stage = SetFix_PRE;                    /*保持已连接时设置参考点坐标*/
                                } else {
                                    stage = MENU_INI;                    /*保持未连接时界面不变*/
                                }
                                break;
                            case 4:
                                if (initG) {
                                    stage = CALIBRATION_CER_PRE;                     /*保持已连接时标定*/
                                } else {
                                    stage = MENU_INI;                                        /*保持未连接时界面不变*/
                                }
                                break;
                            case 5:
                                stage = SysParaInfo_PRE;                                /*系统参数设置及查询*/
                                break;
                            case 6:
                                stage = Beidou_self_destroy_P1;                        /*北斗自毁*/
                                break;
                            default:
                                break;
                        }
                    }
                }
                break;
//
            case MENU_START:
////                    che.puthz16(50,10,2,WHITE,"正常启动");
////                    outtextxy(30,25,"2.");
////                    che.puthz16(50,30,2,WHITE,"快速启动");
////                    settextstyle(DEFAULT_FONT, HORIZ_DIR,	1);
////                    settextjustify(LEFT_TEXT,TOP_TEXT);
////
                MainActivity.instance.setRed(0);
                changeStageUI(FragmentQidong.instance);
                stage = MENU_START_S1;
//
            case MENU_START_S1:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();
                    if (key.type == Key.Esc) {
                        stage = MENU_MAIN;
                    } else if (key.type == Key.ENTER) {
                        switch (key.menu_item) {
                            case 1:
                                stage = START_NM;
                                ini_mode = INI_NM;
                                break;
                            case 2:
                                stage = START_NM;
                                ini_mode = INI_EX;
                                break;
                            case 3:
                                stage = MENU_START;
                                break;
                            default:
                                break;
                        }
                    }
                }
                break;
//
            case START_NM:
////                    outtextxy(30,5,"1.");
////                    che.puthz16(50,10,2,WHITE,"输入新坐标");
////                    outtextxy(30,25,"2.");
////                    che.puthz16(50,30,2,WHITE,"采用卫星定位值");
////                    settextstyle(textinfo.font,	HORIZ_DIR, 1);
////
////

                changeStageUI(FragmentSart_NM.instance);
                stage = START_NM_S1;

//
            case START_NM_S1:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();
                    if (key.type == Key.Esc) {
                        stage = MENU_START;
                    } else if (key.type == Key.ENTER) {
                        switch (key.menu_item) {
                            case 1:
                                stage = FIX_FORMAT_SEL;
                                HostStage = START_NM;
                                break;
                            case 2:
                                if (GGA_Data_Status > 0 || Num_DWR > 0) {
                                    INS_Ini = 1;
                                    postR = false;
                                    stage = POST;
                                    buf[0] = (byte) 0xf2;

                                    dx = BdX;
                                    dy = BdY;
                                    lh = (short) BdHeight;

                                    buf[1] = (byte) (dx & 0xff);
                                    buf[2] = (byte) ((dx & 0xff00) >> 8);
                                    buf[3] = (byte) ((dx & 0xff0000) >> 16);
                                    buf[4] = (byte) (dy & 0xff);
                                    buf[5] = (byte) ((dy & 0xff00) >> 8);
                                    buf[6] = (byte) ((dy & 0xff0000) >> 16);
                                    buf[7] = (byte) ((dy & 0xff000000L) >> 24);
                                    if ((lh & 0x8000) > 0) {
                                        lhr = (short) (lh & 0x7fff);
                                        lhr -= 1;
                                        buf[8] = (byte) (0xff & ~lhr);
                                        buf[9] = (byte) ((0xff00 & ~lhr) >> 8);
                                        buf[9] |= 0x80;
                                    } else {
                                        buf[8] = (byte) (lh & 0xff);
                                        buf[9] = (byte) ((lh & 0xff00) >> 8);
                                    }
                                    Buf_Com3.PutData(buf, 16);
                                    buf[0] = (byte) 0xfd;
                                    buf[1] = (byte) ini_mode;
                                    Buf_Com3.PutData(buf, 8);
                                } else {
                                    stage = NS_DATA_UNUSED;
                                    HostStage = START_NM;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                break;
//
            case START_NM_NewFix:
//                    che.puthz16(10,5,2,WHITE,"初");
//                    che.puthz16(10,23,2,WHITE,"始");
//                    che.puthz16(10,41,2,WHITE,"坐");
//                    che.puthz16(10,59,2,WHITE,"标");
//                    if(FixFormat==FixGaussPlane)
//                    {
//                        outtextxy(35,6,"X=");
//                        outtextxy(35,26,"Y=");
//                    }
//                    else if(FixFormat==FixGeoOrth)
//                    {
//                        outtextxy(35,6,"B=");
//                        outtextxy(35,26,"L=");
//                    }
//                    else
//                    {
//                        outtextxy(35,6,"X=");
//                        outtextxy(35,26,"Y=");
//                    }

                MainActivity.cszb.input1.set("");
                MainActivity.cszb.input2.set("");
                MainActivity.cszb.input3.set("");

                MainActivity.fragmentManager.beginTransaction()
                        .replace(R.id.contentFrame, FragmentShuRuZuoBiaoV2.instance)
                        .commit();

                if (FragmentShuRuZuoBiaoV2.instance.input1 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input2 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input3 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusableInTouchMode(true);
                }

                if (FixFormat == FixGaussPlane) {
                    MainActivity.cszb.title.set("初始平面坐标");
                    MainActivity.cszb.row1_title.set("X=");
                    MainActivity.cszb.row2_title.set("Y=");

                } else {
                    // todo 需要补经纬度坐标
                    MainActivity.cszb.title.set("初始大地坐标");
                    MainActivity.cszb.row1_title.set("大地纬度B=");
                    MainActivity.cszb.row2_title.set("大地经度L=");
                }
                stage = START_NM_NewFix_S1;
//
            case START_NM_NewFix_S1:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();
                    if (key.type == Esc) {
                        stage = START_NM;
                    } else if (key.type == Key.ENTER) {
                        String input1 = MainActivity.cszb.input1.get();
                        String input2 = MainActivity.cszb.input2.get();
                        String input3 = MainActivity.cszb.input3.get();
                        if (FixFormat == FixGaussPlane) {
                            try {
                                dx = Long.parseLong(input1);
                                dy = Long.parseLong(input2);
                                lh = Short.parseShort(input3);
                            } catch (NumberFormatException e) {
                                MainActivity.alertNoReturn("坐标输入错误,请返回");
                                break;
                            }
                            if (dx < 0 || dx > 9000000 || dy < 0 || dy > 99999999 || lh < -100 || lh > 10000)            /*平面坐标输入错误*/ {
                                MainActivity.alertNoReturn("坐标输入错误,请返回");
                                break;
                            }
                        } else if (FixFormat == FixGeoOrth) {
                            dB = Double.parseDouble(input1);
                            dL = Double.parseDouble(input2);
                            dH = Double.parseDouble(input3);
                            if (dB < -90 || dB > 90 || dL < -180 || dL > 180 || dH < -100 || dH > 10000)                    /*地理坐标输入错误*/ {
                                MainActivity.alertNoReturn("坐标输入错误,请返回");
                                break;
                            }
                        } else {
                            MainActivity.alertNoReturn("不该进入的代码");
                            break;
                        }
                        stage = I_C_CONF;
                    }

                }
                break;
//
            case I_C_CONF:
                if (FixFormat == FixGaussPlane) {
                    MainActivity.cszb.title.set("确认初始平面坐标");
                    MainActivity.cszb.input1.set(String.format(Locale.CHINA, "%d", dx));
                    MainActivity.cszb.input2.set(String.format(Locale.CHINA, "%d", dy));
                    MainActivity.cszb.input3.set(String.format(Locale.CHINA, "%d", lh));
                } else if (FixFormat == FixGeoOrth) {
                    MainActivity.cszb.title.set("确认初始大地坐标");
                    MainActivity.cszb.input1.set(String.format(Locale.CHINA, "[%2.6f]°", dB));
                    MainActivity.cszb.input2.set(String.format(Locale.CHINA, "[%3.5f]°", dL));
                    MainActivity.cszb.input3.set(String.format(Locale.CHINA, "%3.1f", dH));

                }

                stage = I_C_CONF_S1;

                FragmentShuRuZuoBiaoV2.instance.input1.setFocusable(false);
                FragmentShuRuZuoBiaoV2.instance.input2.setFocusable(false);
                FragmentShuRuZuoBiaoV2.instance.input3.setFocusable(false);
//
            case I_C_CONF_S1:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc) {
                        stage = START_NM_NewFix;
                    } else {
                        INS_Ini = 1;
                        postR = false;
                        stage = POST;
                        if (FixFormat == FixGeoOrth) {
                            iBelt = (int) ((dL / 6) + 1);
                            rover.Bl_XY(dB * M_PI / 180., (dL - (6 * iBelt - 3)) * M_PI / 180., X54, Y54, 2);                //参数'2'表示CGCS2000坐标了,X54及Y54只是自用原来的参数.

                            dx = (int) X54.getValue().intValue();
                            dy = (int) (Y54.getValue() + 5e5 + iBelt * 1e6);
                            lh = (short) dH;
                        } else {
                            ;
                        }
                        buf[0] = (byte) 0xf2;
                        buf[1] = (byte) ((int) dx & 0xff);
                        buf[2] = (byte) ((dx & 0xff00) >> 8);
                        buf[3] = (byte) ((dx & 0xff0000) >> 16);
                        buf[4] = (byte) (dy & 0xff);
                        buf[5] = (byte) ((dy & 0xff00) >> 8);
                        buf[6] = (byte) ((dy & 0xff0000) >> 16);
                        buf[7] = (byte) ((dy & 0xff000000L) >> 24);
                        if ((lh & 0x8000) > 0) {
                            lhr = (short) (lh & 0x7fff);
                            lhr -= 1;
                            buf[8] = (byte) (0xff & ~lhr);
                            buf[9] = (byte) ((0xff00 & ~lhr) >> 8);
                            buf[9] |= 0x80;
                        } else {
                            buf[8] = (byte) (lh & 0xff);
                            buf[9] = (byte) ((lh & 0xff00) >> 8);
                        }
                        Buf_Com3.PutData(buf, 16);
                        buf[0] = (byte) 0xfd;
                        buf[1] = (byte) ini_mode;
                        Buf_Com3.PutData(buf, 8);
                    }
                }
                break;
            case POST:                                                                                                                //上电自检
                changeStageUI(FragmentPost.instance);
                stage = POST_S1;
            case POST_S1:
                if (bioskey1()) {
                    KeyEvent key1 = bioskey0();
                    if (key1.type == Esc)
                        stage = INI_CAL_POST_OK;
                } else if (postR) {
                    if (ErrCodeFromBC == 0x0) {
                        stage = INI_CAL_POST_OK;
                    } else {
                        stage = INI_CAL_POST_OK;
                    }
                }
                break;
            case INI_CAL_POST_OK:
                switch (ini_mode) {
                    case INI_NM:
                        tTimeT = Time_Init * 60L;    //正常启动时间15min。
                        break;
                    case INI_EX:
                        tTimeT = (Time_Init - 10) * 60L;    //快速启动时间5min。
                        break;
                    default:
                        tTimeT = Time_Init * 60L;
                        break;
                }
                tTimeR = tTimeT;
                start = System.currentTimeMillis();
                changeStageUI(FragmentIniCal.instance);
                stage = INI_CAL_S1;
            case INI_CAL_S1:
                if (bioskey1()) {
                    KeyEvent key1 = bioskey0();
                    if (key1.type == Esc) {
                        buf[0] = (byte) 0xf8;
                        Buf_Com3.PutData(buf, 8);
                        stage = WIN_NAV_P1_PRE;
                        start = tim();
                    }
                } else if (initG) {
                    buf[0] = (byte) 0xf8;
                    Buf_Com3.PutData(buf, 8);
                    stage = WIN_NAV_P1_PRE;
                    start = tim();
                } else if (timeFlag > 0) {
                    timeFlag = 0;
                    tTimeR = tTimeT - TimeUnit.MILLISECONDS.toSeconds(tim() - start);
                    MainActivity.timerData.time.set(String.format(Locale.CHINA, "%02d:%02d", (tTimeR / 60) % 60, tTimeR % 60));

                } else {
                }
                break;
            case WIN_NAV_P1_PRE:
                MainActivity.instance.setRed(1);
                changeStageUI(FragmentDaohang.instance);
                stage = WIN_NAV_P1;
            case WIN_NAV_P1:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc)
                        stage = MENU_MAIN;
//                    else if (keyEvent.type == Enter && keyEvent.menu_item == 2) {
//                        stage = WIN_NAV_P2_PRE;
//                    }
                } else if (timeFlag > 0) {
                    timeFlag = 0;
                    tTimeR = TimeUnit.MILLISECONDS.toSeconds(tim() - start);
                    /*密位转换成度*/
                    MainActivity.daoHangData.la.set(String.format("%5.1f", la * 360 / 6000));
                    MainActivity.daoHangData.ux1.set(String.format("%d", ux1));
                    MainActivity.daoHangData.uy1.set(String.format("%d", uy1));
                    MainActivity.daoHangData.uh1.set(String.format("%d", uh1));
                    MainActivity.daoHangData.velocity.set(String.format("%5.1f", velocity * 3.6));
                    MainActivity.daoHangData.ud.set(String.format("%d", ud));
                    MainActivity.daoHangData.time.set(String.format("%2d:%2d:%2d", tTimeR / 3600, (tTimeR / 60) % 60, tTimeR % 60));
                    MainActivity.daoHangData.pitch.set(String.format("%6.2f", pitch));
                    MainActivity.daoHangData.roll.set(String.format("%6.2f", roll));

                    MainActivity.daoHangData.BdJingdu.set(String.format("%c : %-2.4f", BdLatitude_Dir, BdLatitude));
                    MainActivity.daoHangData.BdWeiDu.set(String.format("%c : %-3.4f", BdLongitude_Dir, BdLongitude));
                    MainActivity.daoHangData.BdX.set(String.format("%d", BdX));
                    MainActivity.daoHangData.BdY.set(String.format("%d", BdY));
                    MainActivity.daoHangData.BdHeight.set(String.format("%d", BdHeight));
                    if (GGA_Data_Status == 0 && Num_DWR > 0)                                    //没有GGA定位数据,有RDSS的DWR定位数据,采用DWR定位数据.这里作提示.
                    {
                        MainActivity.daoHangData.rdss.set("有源RDSS定位!");
                    } else {
                        MainActivity.daoHangData.rdss.set("");
                    }
                } else {
                }
                break;
//            case WIN_NAV_P2_PRE:
//                MainActivity.fragmentManager.beginTransaction()
//                        .replace(R.id.daohang_contentFrame, FragmentDaohangBeidou.instance)
//                        .commit();
//                stage = WIN_NAV_P2;
//            case WIN_NAV_P2:
//                if (bioskey1()) {
//                    KeyEvent keyEvent = bioskey0();
//                    if (keyEvent.type == Key.ENTER && keyEvent.menu_item == 1) {
//                        stage = WIN_NAV_P1_PRE;
//                    } else if (keyEvent.type == Esc) {
//                        stage = MENU_MAIN;
//                    }
//                } else if (timeFlag > 0) {
//                    timeFlag = 0;
//                    MainActivity.daoHangData.BdJingdu.set(String.format("%c : %-2.4f", BdLatitude_Dir, BdLatitude));
//                    MainActivity.daoHangData.BdWeiDu.set(String.format("%c : %-3.4f", BdLongitude_Dir, BdLongitude));
//                    MainActivity.daoHangData.BdX.set(String.format("%d", BdX));
//                    MainActivity.daoHangData.BdY.set(String.format("%d", BdY));
//                    MainActivity.daoHangData.BdHeight.set(String.format("%d", BdHeight));
//                    if (GGA_Data_Status == 0 && Num_DWR > 0)                                    //没有GGA定位数据,有RDSS的DWR定位数据,采用DWR定位数据.这里作提示.
//                    {
//                        MainActivity.daoHangData.rdss.set("有源RDSS定位!");
//                    } else {
//                        MainActivity.daoHangData.rdss.set("");
//                    }
//                }
//                break;
//// todo 迁移java
            case DRIFT_CAL_PRE:
                MainActivity.instance.setRed(3);
                changeStageUI(FragmentCepiao.instance);
                stage = DRIFT_CAL_CONF;
            case DRIFT_CAL_CONF:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc) {
                        stage = MENU_MAIN;
                    } else if (keyEvent.type == Enter) {
                        buf[0] = (byte) 0xe1;
                        buf[1] = (byte) Time_DriftCal;
                        Buf_Com3.PutData(buf, 8);

                        testDT = 0;
                        tTimeT = Time_DriftCal * 60L;
                        tTimeR = tTimeT;
                        start = tim();
                        stage = DRIFT_CAL;
                        changeStageUI(FragmentCepiaoCountdown.instance);

                    }
                }

                break;

            case DRIFT_CAL:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc) {
                        stage = MENU_MAIN;
                    }
                } else if (testDT > 0) {
                    testDT = 0;
                    buf[0] = (byte) 0xf8;
                    Buf_Com3.PutData(buf, 8);
                    stage = WIN_NAV_P1_PRE;
                    start = tim();
                } else if (timeFlag > 0) {
                    timeFlag = 0;
                    {
                        tTimeR = TimeUnit.MILLISECONDS.toSeconds(tim() - start);
                        MainActivity.timerData.time.set(String.format("%02d:%02d", (tTimeR / 60) % 60, tTimeR % 60));

                    }
                } else {

                }
                break;
            case ALIGN_PRE:
                MainActivity.instance.setRed(2);
                changeStageUI(FragmentXunbei.instance);
                stage = ALIGN;
            case ALIGN:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc) {
                        stage = MENU_MAIN;
                    } else if (keyEvent.type == Enter) {
                        switch (keyEvent.menu_item) {
                            case 1:                                                /*新坐标*/
                                stage = FIX_FORMAT_SEL;
                                HostStage = ALIGN_PRE;
                                break;
                            case 2:                                                /*卫星值*/
                                if (GGA_Data_Status > 0 || Num_DWR > 0)                                        /*RNSS定位有效或有过一次以上RDSS定位*/ {
                                    buf[0] = (byte) 0xf2;
                                    dx = BdX;
                                    dy = BdY;
                                    lh = (short) BdHeight;

                                    buf[1] = (byte) (dx & 0xff);
                                    buf[2] = (byte) ((dx & 0xff00) >> 8);
                                    buf[3] = (byte) ((dx & 0xff0000) >> 16);
                                    buf[4] = (byte) (dy & 0xff);
                                    buf[5] = (byte) ((dy & 0xff00) >> 8);
                                    buf[6] = (byte) ((dy & 0xff0000) >> 16);
                                    buf[7] = (byte) ((dy & 0xff000000L) >> 24);
                                    if ((lh & 0x8000) > 0) {
                                        lhr = (short) (lh & 0x7fff);
                                        lhr -= 1;
                                        buf[8] = (byte) (0xff & ~lhr);
                                        buf[9] = (byte) ((0xff00 & ~lhr) >> 8);
                                        buf[9] |= 0x80;
                                    } else {
                                        buf[8] = (byte) (lh & 0xff);
                                        buf[9] = (byte) ((lh & 0xff00) >> 8);
                                    }
                                    Buf_Com3.PutData(buf, 16);
                                    stage = ALIGN_S1_PRE;
                                } else {
                                    stage = NS_DATA_UNUSED;
                                    HostStage = ALIGN_PRE;
                                }
                                break;
                            case 3:                                                /*解算值*/
                                stage = ALIGN_S1_PRE;
                                buf[0] = (byte) 0xe2;
                                Buf_Com3.PutData(buf, 8);
                                break;
                            default:
                                break;
                        }
                    }
                }
                break;
//
            case NS_DATA_UNUSED:
                MainActivity.alertAndReturn(NS_DATA_UNUSED_MSG);

                stage = NS_DATA_UNUSED_S1;

            case NS_DATA_UNUSED_S1:
                if (bioskey1() && bioskey0().type == Esc) {

                    if (HostStage == ALIGN_PRE) {
                        stage = ALIGN_PRE;
                    } else if (HostStage == START_NM) {
                        stage = START_NM;
                    } else {
                        stage = MENU_MAIN;
                    }
                }
                break;
//
            case FIX_FORMAT_SEL:

                MainActivity.fragmentManager.beginTransaction()
                        .replace(R.id.contentFrame, FragmentFixFormatSel.instance)
                        .commit();
                stage = FIX_FORMAT_SEL_S1;
            case FIX_FORMAT_SEL_S1:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();

                    if (keyEvent.type == Esc) {
                        stage = HostStage;
                    } else if (keyEvent.type == Enter) {
                        switch (keyEvent.menu_item) {
                            case 1:
                                FixFormat = FixGaussPlane;
                                break;
                            case 2:
                                FixFormat = FixGeoOrth;
                                break;
                            default:
                                break;
                        }
                        if (HostStage == START_NM) {
                            stage = START_NM_NewFix;
                        } else if (HostStage == ALIGN_PRE) {
                            stage = ALIGN_COR_NEW_PRE;
                        } else {
                            stage = WIN_NAV_P1_PRE;
                        }

                    }
                }
                break;
//
            case ALIGN_COR_NEW_PRE:
                MainActivity.fragmentManager.beginTransaction()
                        .replace(R.id.contentFrame, FragmentShuRuZuoBiaoV2.instance)
                        .commit();

                if (FragmentShuRuZuoBiaoV2.instance.input1 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input2 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input3 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusableInTouchMode(true);
                }

                if (FixFormat == FixGaussPlane) {
                    MainActivity.cszb.title.set("初始平面坐标");
                    MainActivity.cszb.row1_title.set("X=");
                    MainActivity.cszb.row2_title.set("Y=");

                } else {

                    MainActivity.cszb.title.set("初始大地坐标");
                    MainActivity.cszb.row1_title.set("B=");
                    MainActivity.cszb.row2_title.set("L=");
                }

                stage = ALIGN_COR_NEW;
//
            case ALIGN_COR_NEW:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc)                            /*按Esc键退出到寻北准备界面*/ {
                        stage = ALIGN_PRE;
                    } else if (keyEvent.type == Enter)                    /*按Enter键确认输入*/ {

                        String input1 = MainActivity.cszb.input1.get();
                        String input2 = MainActivity.cszb.input2.get();
                        String input3 = MainActivity.cszb.input3.get();
                        if (FixFormat == FixGaussPlane) {
                            try {
                                dx = Long.parseLong(input1);
                                dy = Long.parseLong(input2);
                                lh = Short.parseShort(input3);
                            } catch (NumberFormatException e) {
                                MainActivity.alertNoReturn("坐标输入错误,请返回");
                                break;
                            }
                            if (dx < 0 || dx > 9000000 || dy < 0 || dy > 99999999 || lh < -100 || lh > 10000)            /*平面坐标输入错误*/ {
                                MainActivity.alertNoReturn("坐标输入错误,请返回");
                                break;
                            }
                        } else if (FixFormat == FixGeoOrth) {

                            dB = Double.parseDouble(input1);
                            dL = Double.parseDouble(input2);
                            dH = Double.parseDouble(input3);
                            if (dB < -90 || dB > 90 || dL < -180 || dL > 180 || dH < -100 || dH > 10000)                    /*地理坐标输入错误*/ {
                                MainActivity.alertNoReturn("坐标输入错误,请返回");
                                break;
                            }
                        } else {
                            MainActivity.alertNoReturn("不该进入的代码");
                            break;
                        }
                        stage = ALIGN_COR_NEW_CONF_PRE;

                    }

                }
                break;
//
//                        case COR_INPUT_ERROR:
//                            Clr_scr();
//                            setviewport(MAXX / 2 - 80, MAXY / 2 - 39, MAXX / 2 + 79 + 30, MAXY / 2 + 40, 1);
//                            setcolor(WHITE);
//                            rectangle(0, 0, OWndX - 1 + 30, OWndY - 1);
//                            che.puthz16a(25, 20, 2, WHITE, "坐标输入错误");
//                            che.puthz16(43, 50, 2, WHITE, "按任意键返回");
//
//                            stage = NS_DATA_UNUSED_S1;
//
//
            case ALIGN_COR_NEW_CONF_PRE:                        /*寻北时输入坐标确认界面*/
                if (FixFormat == FixGaussPlane) {
                    MainActivity.cszb.title.set("确认初始平面坐标");
                    MainActivity.cszb.input1.set(String.format(Locale.CHINA, "%d", dx));
                    MainActivity.cszb.input2.set(String.format(Locale.CHINA, "%d", dy));
                    MainActivity.cszb.input3.set(String.format(Locale.CHINA, "%d", lh));
                } else if (FixFormat == FixGeoOrth) {
                    MainActivity.cszb.title.set("确认初始大地坐标");
                    MainActivity.cszb.input1.set(String.format(Locale.CHINA, "%2.6f", dB));
                    MainActivity.cszb.input2.set(String.format(Locale.CHINA, "%3.5f", dL));
                    MainActivity.cszb.input3.set(String.format(Locale.CHINA, "%3.1f", dH));

                }


                FragmentShuRuZuoBiaoV2.instance.input1.setFocusable(false);
                FragmentShuRuZuoBiaoV2.instance.input2.setFocusable(false);
                FragmentShuRuZuoBiaoV2.instance.input3.setFocusable(false);

                stage = ALIGN_COR_NEW_CONF;
//
            case ALIGN_COR_NEW_CONF:                            /*确认输入坐标*/
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc) {
                        stage = ALIGN_COR_NEW_PRE;            /*按ESC键重新输入*/
                    }
                    /* 按Enter键发送坐标值和寻北命令	 2010-6-8	11:19:29*/
                    else if (keyEvent.type == Enter) {
                        stage = ALIGN_S1_PRE;
                        if (FixFormat == FixGeoOrth) {
                            iBelt = (int) ((dL / 6) + 1);
                            rover.Bl_XY(dB * M_PI / 180., (dL - (6 * iBelt - 3)) * M_PI / 180., X54,
                                    Y54, 2);                        //参数'2'表示CGCS2000坐标了,X54及Y54只是自用原来的参数.
                            dx = X54.getValue().intValue();
                            dy = (int) (Y54.getValue() + 5e5 + iBelt * 1e6);
                            lh = (short) dH;
                        } else {
                            ;
                        }
                        buf[0] = (byte) 0xf2;
                        buf[1] = (byte) (dx & 0xff);
                        buf[2] = (byte) ((dx & 0xff00) >> 8);
                        buf[3] = (byte) ((dx & 0xff0000) >> 16);
                        buf[4] = (byte) (dy & 0xff);
                        buf[5] = (byte) ((dy & 0xff00) >> 8);
                        buf[6] = (byte) ((dy & 0xff0000) >> 16);
                        buf[7] = (byte) ((dy & 0xff000000L) >> 24);
                        if ((lh & 0x8000) > 0) {
                            lhr = (short) (lh & 0x7fff);
                            lhr -= 1;
                            buf[8] = (byte) (0xff & ~lhr);
                            buf[9] = (byte) ((0xff00 & ~lhr) >> 8);
                            buf[9] |= 0x80;
                        } else {
                            buf[8] = (byte) (lh & 0xff);
                            buf[9] = (byte) ((lh & 0xff00) >> 8);
                        }
                        Buf_Com3.PutData(buf, 16);
                    } else {
                        ;
                    }
                }
                break;
//
            case ALIGN_S1_PRE:
                changeStageUI(FragmentXunbeiCountdown.instance);

                NF_OnRun = true;
                buf[0] = (byte) 0xe2;
                Buf_Com3.PutData(buf, 8);
                norFT = 0;
                tTimeT = Time_NorthFinder * 60L;
                tTimeR = tTimeT;
                start = tim();
//                            count = 0;
                stage = ALIGN_S1;
//
            case ALIGN_S1:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == TAB) {
                        stage = ALIGN_PRE;
                        NF_OnRun = false;
                    }

                } else if (norFT > 0) {
                    buf[0] = (byte) 0xf8;
                    Buf_Com3.PutData(buf, 8);

                    NF_OnRun = false;

                    if (norFT == 0x01) {
                        if ((ErrCodeFromBC & 0x0010) > 0) {
                        } else {
                        }
                        stage = WIN_NAV_P1_PRE;
                        start = tim();
                    } else if (norFT == 0x02) {
                        stage = NorthFinderFault_PRE;
                        start = tim();
                    } else {
                        stage = WIN_NAV_P1_PRE;
                        start = tim();
                    }

                    norFT = 0;
                } else if (timeFlag > 0) {
                    timeFlag = 0;
                    tTimeR = tTimeT - TimeUnit.MILLISECONDS.toSeconds(tim() - start);
                    if (tTimeR >= 0) {
                        MainActivity.timerData.time.set(String.format(Locale.CHINA, "%02d:%02d", (tTimeR / 60) % 60, tTimeR % 60));
                    }
                } else if (tTimeR < 0) {
                    // 超时了，寻北失败
                    buf[0] = (byte) 0xf8;
                    Buf_Com3.PutData(buf, 8);

                    NF_OnRun = false;

                    stage = NorthFinderFault_PRE;
                    start = tim();
                } else {

                }
                break;
//
            case NorthFinderFault_PRE:
                buf[0] = (byte) 0xf0;
                Buf_Com3.PutData(buf, 8);
                stage = NorthFinderFault_S1;
                MainActivity.alertAndReturn("寻北失败，数据无效");
//
            case NorthFinderFault_S1:
                if (bioskey1() && bioskey0().type == Esc) {
                    stage = WIN_NAV_P1_PRE;
                }
                break;
//
            case CALIBRATION_CER_PRE:
                changeStageUI(FragmentSysParaInfoSet.instance);
                stage = CALIBRATION_CER;
//
            case CALIBRATION_CER:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();

                    if (keyEvent.type == Esc) {
                        stage = MENU_INI;
                    } else if (keyEvent.type == Enter) {
                        String pwd = keyEvent.extra.getOrDefault("pwd", "");
                        if (password.equals(pwd)) {
                            stage = CALIBRATION_PRE;
                        } else {
                            stage = MENU_INI;
                        }
                    }
                }
                break;
//
            case CALIBRATION_PRE:
                FixFormat = FixGaussPlane;
                changeStageUI(FragmentShuRuZuoBiaoV2.instance);
                if (FragmentShuRuZuoBiaoV2.instance.input1 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input2 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input3 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusableInTouchMode(true);
                }

                MainActivity.cszb.title.set("输入起点坐标");
                MainActivity.cszb.row1_title.set("X=");
                MainActivity.cszb.row2_title.set("Y=");


                calOk = 0;
                stage = CALIBRATION_S1;
//
            case CALIBRATION_S1:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    Key ch = keyEvent.type;
                    if (ch == Esc) {
                        stage = MENU_INI;
                    } else if (ch == Enter) {

                        String input1 = MainActivity.cszb.input1.get();
                        String input2 = MainActivity.cszb.input2.get();
                        String input3 = MainActivity.cszb.input3.get();
                        try {
                            dx = Long.parseLong(input1);
                            dy = Long.parseLong(input2);
                            lh = Short.parseShort(input3);
                        } catch (NumberFormatException e) {
                            MainActivity.alertNoReturn("坐标输入错误,请返回");
                            break;
                        }
                        if (dx < 0 || dx > 9000000 || dy < 0 || dy > 99999999 || lh < -100 || lh > 10000)            /*平面坐标输入错误*/ {
//                                            stage = CALIBRATION_PRE;
                            MainActivity.alertNoReturn("坐标输入错误,请返回");

                            break;
                        }
                        buf[0] = (byte) 0xf5;
                        buf[1] = (byte) (dx & 0xff);
                        buf[2] = (byte) ((dx & 0xff00) >> 8);
                        buf[3] = (byte) ((dx & 0xff0000) >> 16);
                        buf[4] = (byte) (dy & 0xff);
                        buf[5] = (byte) ((dy & 0xff00) >> 8);
                        buf[6] = (byte) ((dy & 0xff0000) >> 16);
                        buf[7] = (byte) ((dy & 0xff000000L) >> 24);
                        if ((lh & 0x8000) > 0) {
                            lhr = (short) (lh & 0x7fff);
                            lhr -= 1;
                            buf[8] = (byte) (0xff & ~lhr);
                            buf[9] = (byte) ((0xff00 & ~lhr) >> 8);
                            buf[9] |= 0x80;
                        } else {
                            buf[8] = (byte) (lh & 0xff);
                            buf[9] = (byte) ((lh & 0xff00) >> 8);
                        }
                        stage = CALIBRATION_S2;
                        Buf_Com3.PutData(buf, 16);
                        MainActivity.alertAndReturn("标定开始，点击返回结束");
                    }
                }
                break;
//
            case CALIBRATION_S2:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    stage = CALIBRATION_S3;
                }
                break;
//
            case CALIBRATION_S3:
                changeStageUI(FragmentShuRuZuoBiaoV2.instance);

                MainActivity.cszb.input1.set("");
                MainActivity.cszb.input2.set("");
                MainActivity.cszb.input3.set("");

                if (FragmentShuRuZuoBiaoV2.instance.input1 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input2 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input3 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusableInTouchMode(true);
                }

                MainActivity.cszb.title.set("输入终点坐标");
                MainActivity.cszb.row1_title.set("X=");
                MainActivity.cszb.row2_title.set("Y=");

                stage = CALIBRATION_S4;
//
            case CALIBRATION_S4:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();

                    if (keyEvent.type == Esc) {
                        ;
                    } else if (keyEvent.type == Enter) {
                        String input1 = MainActivity.cszb.input1.get();
                        String input2 = MainActivity.cszb.input2.get();
                        String input3 = MainActivity.cszb.input3.get();
                        try {
                            dx = Long.parseLong(input1);
                            dy = Long.parseLong(input2);
                            lh = Short.parseShort(input3);
                        } catch (NumberFormatException e) {
                            MainActivity.alertNoReturn("坐标输入错误,请返回");
                            break;
                        }

                        if (dx < 0 || dx > 9000000 || dy < 0 || dy > 99999999 || lh < -100 || lh > 10000)            /*平面坐标输入错误*/ /*2010-6-6	10:04:03*/ {
//                            stage = CALIBRATION_S3;
                            MainActivity.alertNoReturn("坐标输入错误,请返回");
                            break;
                        }
                        buf[0] = (byte) 0xf6;
                        buf[1] = (byte) (dx & 0xff);
                        buf[2] = (byte) ((dx & 0xff00) >> 8);
                        buf[3] = (byte) ((dx & 0xff0000) >> 16);
                        buf[4] = (byte) (dy & 0xff);
                        buf[5] = (byte) ((dy & 0xff00) >> 8);
                        buf[6] = (byte) ((dy & 0xff0000) >> 16);
                        buf[7] = (byte) ((dy & 0xff000000L) >> 24);
                        if ((lh & 0x8000) > 0) {

                            lhr = (short) (lh & 0x7fff);
                            lhr -= 1;
                            buf[8] = (byte) (0xff & ~lhr);
                            buf[9] = (byte) ((0xff00 & ~lhr) >> 8);
                            buf[9] |= 0x80;
                        } else {
                            buf[8] = (byte) (lh & 0xff);
                            buf[9] = (byte) ((lh & 0xff00) >> 8);
                        }
                        Buf_Com3.PutData(buf, 16);
                        countFlag = tim();
                        timeFlag = 0;
                        stage = CALIBRATION_S5;

                    }
                }
                break;
//
            case CALIBRATION_S5:
                changeStageUI(FragmentCalibrationS5.instance);
                if (calOk > 0) {
                    calOk = 0;
                    stage = CALIBRATION_S6_PRE;
                } else if (TimeUnit.MILLISECONDS.toSeconds(tim() - countFlag) > 10) {
                   // 超时
                    timeFlag = 0;
                    countFlag = tim();
                    MainActivity.alertAndReturn("参数计算失败");
                    stage = CALIBRATION_S6;
                } else {
                    if (bioskey1()) {
                        if (bioskey0().type == Esc) {
                            stage = MENU_INI;
                        }
                    }
                }
                break;
//
            case CALIBRATION_S6_PRE:
                MainActivity.paraSetData.text1.set(String.format(Locale.CHINA, "%6.4f", k));
                MainActivity.paraSetData.text2.set(String.format(Locale.CHINA, "%.1f", mntErr * M_PI / 3));
                changeStageUI(FragmentGetMntErr.instance);
                stage = CALIBRATION_S6;
            case CALIBRATION_S6:
                if (bioskey1()) {
                    if (bioskey0().type == Esc) {
                        stage = MENU_INI;
                    }
                }
                break;
//
            case SysParaInfo_PRE:
                MainActivity.fragmentManager.beginTransaction().replace(R.id.contentFrame, FragmentSysParaInfo.instance).commit();

                stage = SysParaInfo_S1;
//
            case SysParaInfo_S1:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();

                    if (key.type == Key.Esc) {
                        stage = MENU_INI;
                    } else if (key.type == Key.ENTER) {
                        switch (key.menu_item) {
                            case 1:
                                stage = SysParaInfo_S2;
                                break;
                            case 2:
                                stage = GetMntErr_PRE;
                                break;
                            default:
                                break;
                        }
                    }
                }
                break;
//
            case SysParaInfo_S2:
                stage = SysParaInfo_S3;

            case SysParaInfo_S3:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();

                    if (key.type == Key.Esc) {
                        stage = SysParaInfo_PRE;
                    } else if (key.type == Key.ENTER) {
                        String pwd = key.extra.getOrDefault("pwd", "");
                        if (password.equals(pwd)) {
                            stage = PARA_SET_PRE;

                        } else {
                            stage = SysParaInfo_PRE;

                        }
//                                    pwd = atol(data_buf[0]);
//                                    if (pwd == 68912543) {
//                                        stage = PARA_SET_PRE;
//                                    } else {
//                                    stage = SysParaInfo_PRE;
//                                    }

                    }
                }
                break;
//
            case Beidou_self_destroy_P1:
//                            Clr_scr();
//                            che.puthz16a(104, 20, 2, WHITE, "警 告");
//                            che.puthz16(46, 60, 2, WHITE, "北斗将不可逆毁坏！");
//                            che.puthz16(36, 100, 2, WHITE, "返回按");
//                            che.puthz16(150, 100, 2, WHITE, "继续按");
//                            outtextxy(94, 100, "Esc;");
//                            outtextxy(204, 100, "-->");
                changeStageUI(FragmentBeidouZihuiP1.instance);
//                            FragmentBeidouZihui.instance.changeTitle("北斗将不可逆毁坏！！！");
                stage = Beidou_self_destroy_S1;
//
            case Beidou_self_destroy_S1:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    Key ch = keyEvent.type;
                    if (ch == Esc) {
                        stage = MENU_INI;
                    } else if (ch == Enter) {
                        stage = Beidou_self_destroy_P2;
                    } else {
                        ;
                    }
                }
                break;
//
            case Beidou_self_destroy_P2:
//                            Clr_scr();
//                            che.puthz16a(78, 20, 2, WHITE, "最 后 警 告");
//                            che.puthz16(34, 60, 2, WHITE, "你将发送北斗自毁命令！");
//                            che.puthz16(34, 100, 2, WHITE, "返回按");
//                            che.puthz16(148, 100, 2, WHITE, "确认按");
//                            outtextxy(94, 100, "Esc;");
//                            outtextxy(204, 100, "Enter");
                changeStageUI(FragmentBeidouZihuiP2.instance);
                stage = Beidou_self_destroy_S2;
//
            case Beidou_self_destroy_S2:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    Key ch = keyEvent.type;
                    if (ch == Esc) {
                        stage = MENU_INI;
                    } else if (ch == Enter) {
                        send_string_com(COM4, 20, ZHS);                    //往北斗发送自毁命令
                        Date date = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String currentTime = sdf.format(date);
                        String text = String.format("Command send once at %s \n", currentTime);
                        writeBDZH(text);
                        ;
//                                    fp_BDZH = fopen("BDZH.txt", "a+t");            //Recording each time operation Here 20161228
//                                    if (fp_BDZH) {
//                                        fseek(fp_BDZH, 0, SEEK_END);
//                                        fprintf(fp_BDZH, "Command send once at %s.%s.%s \n", BDZH_data.year, BDZH_data.month, BDZH_data.day);
//                                    }
//                                    fclose(fp_BDZH);

                        stage = Beidou_self_destroy_P3;
                    } else {
                        ;
                    }
                }

                break;
//
////			case Beidou_self_destroy_second_S2:																		//没有等待北斗返回自毁结果
////					Clr_scr();
////					setviewport(MAXX/2-110,MAXY/2-40,MAXX/2+110,MAXY/2+40,1);
////					setcolor(WHITE);
////					rectangle(0,0,219,79);
////					che.puthz16a(14,20,2,WHITE,"已经发送北斗自毁命令！");
////					che.puthz16(50,50,2,WHITE,"按");
////					che.puthz16(94,50,2,WHITE,"键返回");
////					gettextsettings(&textinfo);
////					settextstyle(SMALL_FONT, HORIZ_DIR,	5);
////					settextjustify(LEFT_TEXT,TOP_TEXT);
////					outtextxy(68,50,"Esc");
////					settextstyle(textinfo.font, HORIZ_DIR,1);
////					stage=Beidou_self_destroy_second_S3;
////
////			case Beidou_self_destroy_second_S3:
////					if(bioskey(1))
////						{
////							key1=key2=bioskey(0);
////							ch=key1&0xff;
////						  key2=key2&0xff?0:key2>>8;
////							if(ch==Esc)
////								 {
////										stage=MENU_INI;
////								 }
////						}
////			break;
//
            case Beidou_self_destroy_P3:                                                                        //等待北斗返回自毁结果
//                            Clr_scr();
//                            che.puthz16a(104, 20, 2, WHITE, "提 示");
//                            che.puthz16(34, 60, 2, WHITE, "已经发送北斗自毁命令！");
//                            che.puthz16a(34, 100, 2, WHITE, "请等待反馈状态...");
//                            count = 0;
                FKI_ZHS = 0;
                timeFlag = 0;
                countFlag = tim();
                changeStageUI(FragmentBeidouZihuiP3.instance);
                stage = Beidou_self_destroy_S3;
//
            case Beidou_self_destroy_S3:
                if (FKI_ZHS == 'Y')                                                //自毁成功
                {
                    stage = Beidou_self_destroy_P4;
                } else if (FKI_ZHS == 'N')                                        //自毁失败
                {
                    stage = Beidou_self_destroy_P5;
                } else if (TimeUnit.MILLISECONDS.toSeconds(tim() - countFlag) > 10)                                                //约5秒内没有接收到返回
                {
                    stage = Beidou_self_destroy_P6;
                } else {
                    ;
                }
                break;
//
            case Beidou_self_destroy_P4:                                                                        //北斗自毁指令执行成功
//                            Clr_scr();
//                            che.puthz16a(104, 20, 2, WHITE, "提 示");
//                            che.puthz16(34, 60, 2, WHITE, "北斗自毁指令执行成功！");
//                            che.puthz16(34, 100, 2, WHITE, "返回按");
//                            outtextxy(94, 100, "Esc");
                changeStageUI(FragmentBeidouZihuiP4.instance);
                stage = Beidou_self_destroy_S4;
                break;

            case Beidou_self_destroy_P5:                                                                        //北斗自毁指令执行失败
//                            Clr_scr();
//                            che.puthz16a(104, 20, 2, WHITE, "注 意");
//                            che.puthz16(34, 60, 2, WHITE, "北斗自毁指令执行失败！");
//                            che.puthz16(34, 100, 2, WHITE, "返回按");
//                            outtextxy(94, 100, "Esc");
                changeStageUI(FragmentBeidouZihuiP5.instance);
                stage = Beidou_self_destroy_S4;
                break;

            case Beidou_self_destroy_P6:                                                                        //发送北斗自毁命令没接收到反馈语句
//                            Clr_scr();
//                            che.puthz16a(104, 20, 2, WHITE, "注 意");
//                            che.puthz16(34, 60, 2, WHITE, "没收到自毁反馈语句！");
//                            che.puthz16(34, 100, 2, WHITE, "返回按");
//                            outtextxy(94, 100, "Esc");
                changeStageUI(FragmentBeidouZihuiP6.instance);
                stage = Beidou_self_destroy_S4;
                break;

            case Beidou_self_destroy_S4:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    Key ch = keyEvent.type;
                    if (ch == Esc) {
                        stage = MENU_INI;
                    }
                }
                break;
//
            case PARA_SET_PRE:
//                            che.puthz16(10, 10, 2, WHITE, "安装误差");
//                            che.puthz16(10, 30, 2, WHITE, "里程系数");

                MainActivity.paraSetData.text1.set("");
                MainActivity.paraSetData.text2.set("");
                MainActivity.fragmentManager.beginTransaction().replace(R.id.contentFrame, FragmentParaSet.instance).commit();
                stage = PARA_SET_S1;
//
            case PARA_SET_S1:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Key.Esc) {
                        stage = SysParaInfo_PRE;
                    } else if (keyEvent.type == Enter) {
                        mntErr = Double.parseDouble(keyEvent.extra.getOrDefault("mntErr", "0")) * 3 / M_PI;
                        k = Double.parseDouble(keyEvent.extra.getOrDefault("k", "0"));
//                                        mntErr = atof(data_buf[0]) * 3 / M_PI;                                                /*安装误差mrad*/
//                                        k = atof(data_buf[1]);

                        if (mntErr < -3276.8 || mntErr > 3276.7 || k < 0 || k > 6.5535)                /*安装误差或里程系数设置错误，输入时显示约3431豪弧。*/ {
                            MainActivity.alertNoReturn("参数输入错误");
                            stage = PARA_SET_PRE;
                            break;
                        }
                        stage = PARA_SET_S2;
                    }
                }
                break;
//
            case PARA_SET_S2:
//                            sprintf(cuxyz, "%.1f", mntErr * M_PI / 3);
//                            outtextxy(100, 15, cuxyz);
//                            sprintf(cuxyz, "%6.4f", k);
//                            outtextxy(100, 35, cuxyz);
                MainActivity.paraSetData.text1.set(String.format(Locale.CHINA, "%.1f", mntErr * M_PI / 3));
                MainActivity.paraSetData.text2.set(String.format(Locale.CHINA, "%6.4f", k));
                MainActivity.fragmentManager.beginTransaction()
                        .replace(R.id.contentFrame, FragmentParaSetS2.instance)
                        .commit();
                stage = PARA_SET_S3;
//
            case PARA_SET_S3:
                if (bioskey1()) {

                    KeyEvent key1 = bioskey0();
                    if (key1.type == Esc) {
                        stage = PARA_SET_PRE;
                    } else if (key1.type == Enter) {
                        stage = SysParaInfo_PRE;

                        buf[0] = (byte) 0xf3;
                        long roundK = Math.round(k * 1e4);
//                                    if (modf(k * 1e4, & iPart)<
//                                    0.5)                            /*取小数点后4位值,k值的取值应不大于6.5535,*/
//                                    {
//                                        laDeg.uint16 = (int) floor(k * 1e4);
//                                    }
//								else
//                                    {
//                                        laDeg.uint16 = (int) ceil(k * 1e4);
//                                    }
//                                    buf[1] = laDeg. int[0];
//                                    buf[2] = laDeg. int[1];
                        buf[1] = (byte) (roundK & 0xff);
                        buf[2] = (byte) (roundK >> 8);

                        long roundmntErr = Math.round(mntErr * 10);

//                                    if (fabs(modf(mntErr * 10, & iPart))<
//                                    0.5)        /*取小数点后1位值，mntErr范围在-3276.8到3276.7之间*/
//                                    {
//                                        if (mntErr < 0) {
//                                            Ht.sint16 = (int) ceil(mntErr * 10);
//                                        } else {
//                                            Ht.sint16 = (int) floor(mntErr * 10);
//                                        }
//                                    }
//								else
//                                    {
//                                        if (mntErr < 0) {
//                                            Ht.sint16 = (int) floor(mntErr * 10);
//                                        } else {
//                                            Ht.sint16 = (int) ceil(mntErr * 10);
//                                        }
//                                    }
//                                    buf[3] = Ht. int[0];
//                                    buf[4] = Ht. int[1];

                        buf[3] = (byte) (roundmntErr & 0xff);
                        buf[4] = (byte) (roundmntErr >> 8);
                        Buf_Com3.PutData(buf, 8);
                    }

                }
                break;
//
            case GetMntErr_PRE:

                buf[0] = (byte) 0xe4;
                Buf_Com3.PutData(buf, 8);

//                            che.puthz16a(102, 28, 2, WHITE, "系统参数查询");
//                            che.puthz16(10 + uLM, 14 + uTM, 2, WHITE, "安装误差");
//                            che.puthz16(10 + uLM, 44 + uTM, 2, WHITE, "里程系数");
//                            outtextxy(90 + uLM, 18 + uTM, "[");
//                            outtextxy(200 + uLM, 18 + uTM, "] mrad");
//                            outtextxy(90 + uLM, 48 + uTM, "[");
//                            outtextxy(200 + uLM, 48 + uTM, "] mpr");
                //							sprintf(cuxyz,"%4.3f",mntErr*M_PI/3);					/*安装误差*/  //2015-8-7 16:06:46
//                                    sprintf(cuxyz, "%.1f", mntErr * M_PI / 3);                    /*安装误差*/
//                                    outtextxy(120 + uLM, 18 + uTM, cuxyz);
//                                    sprintf(cuxyz, "%3.4f", k);                                            /*里程系数*/
//                                    outtextxy(120 + uLM, 48 + uTM, cuxyz);

                 changeStageUI(FragmentGetMntErr.instance);
                stage = GetMntErr_S1;
//
            case GetMntErr_S1:
                if (bioskey1()) {

                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc) {
                        stage = SysParaInfo_PRE;
                    }
                } else {
                    MainActivity.paraSetData.text1.set(String.format(Locale.CHINA, "%.1f", mntErr * M_PI / 3));
                    MainActivity.paraSetData.text2.set(String.format(Locale.CHINA, "%3.4f", k));
                }
                break;
            case GetBDInfo_PRE:
                            send_string_com(COM4, 19, PMU_OPEN);                    //往北斗用户机发送精测码PMU有效期查询申请
                            send_string_com(COM4, 19, ICM_OPEN);                    //往北斗用户机发送密钥ICM终止期查询申请
//                            che.puthz16a(82, 8, 2, WHITE, "北斗工作状况");
//                            setfillstyle(filltype.pattern, filltype.color);
//                            che.puthz16a(10 + uLM, 5 + uTM, 2, WHITE, "发送器标识符");
//                            che.puthz16a(10 + uLM, 23 + uTM, 2, WHITE, "定位状态指示");
//                            che.puthz16a(10 + uLM, 41 + uTM, 2, WHITE, "视野内卫星数");
//                            che.puthz16a(10 + uLM, 59 + uTM, 2, WHITE, "水平精度因子");
//                            che.puthz16a(10 + uLM, 77 + uTM, 2, WHITE, "垂直精度因子");
//                            che.puthz16a(10 + uLM, 95 + uTM, 2, WHITE, "有源定位次数");
//                            che.puthz16a(10 + uLM, 113 + uTM, 2, WHITE, "密钥终止期");
//                            che.puthz16a(10 + uLM, 131 + uTM, 2, WHITE, "精测码起止期");
//                            outtextxy(248 + uLM, 82 + uTM, "]");
//                            outtextxy(130 + uLM, 100 + uTM, "---- [");
//                            outtextxy(248 + uLM, 100 + uTM, "]");
//                            count = 0;
                changeStageUI(FragmentGetBDInfo.instance);
                stage=GetBDInfo_S1;

            case GetBDInfo_S1:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();
                    if (key.type == Key.Esc) {
                        stage = MENU_INI;
                    }
                } else if (timeFlag > 0) {
                    timeFlag = 0;
//                                if (!(++count % 18)) {
                    if (true) {
//                                    bar(180 + uLM, 6 + uTM, 246 + uLM, 36 + uTM);
//                                    sprintf(cuxyz, "%01c%c", BDchBox[0][1], BDchBox[0][2]);
//                                    outtextxy(200 + uLM, 10 + uTM, cuxyz);
                        MainActivity.bdInfoData.text1.set(String.format("%c%c", BDchBox[0][1], BDchBox[0][2]));
//                                    bar(180 + uLM, 24 + uTM, 246 + uLM, 36 + uTM);
//                                    sprintf(cuxyz, "%02d", GGA_Data_Status);
//                                    outtextxy(200 + uLM, 28 + uTM, cuxyz);
                        MainActivity.bdInfoData.text2.set(String.format(Locale.CHINA, "%02d", GGA_Data_Status));

//                                    bar(180 + uLM, 42 + uTM, 246 + uLM, 54 + uTM);
//                                    sprintf(cuxyz, "%02d", Num_Statelite);
//                                    outtextxy(200 + uLM, 46 + uTM, cuxyz);
                        MainActivity.bdInfoData.text3.set(String.format(Locale.CHINA, "%02d", Num_Statelite));

//                                    bar(180 + uLM, 60 + uTM, 246 + uLM, 72 + uTM);
//                                    sprintf(cuxyz, "%-5.2f", HDOP);
//                                    outtextxy(200 + uLM, 64 + uTM, cuxyz);
                        MainActivity.bdInfoData.text4.set(String.format(Locale.CHINA, "%-5.2f", HDOP));

//                                    bar(180 + uLM, 78 + uTM, 246 + uLM, 90 + uTM);
//                                    sprintf(cuxyz, "%-5.2f", VDOP);
//                                    outtextxy(200 + uLM, 82 + uTM, cuxyz);
                        MainActivity.bdInfoData.text5.set(String.format(Locale.CHINA, "%-5.2f", VDOP));

//                                    bar(180 + uLM, 96 + uTM, 246 + uLM, 108 + uTM);
//                                    sprintf(cuxyz, "%u", Num_DWR);
//                                    outtextxy(200 + uLM, 100 + uTM, cuxyz);
                        MainActivity.bdInfoData.text6.set(String.format(Locale.CHINA, "%d", Num_DWR));

//                                    bar(180 + uLM, 96 + uTM, 246 + uLM, 126 + uTM);
//                                    sprintf(cuxyz, "-%s.%s.%s", ICM_data_To.year, ICM_data_To.month, ICM_data_To.day);
//                                    outtextxy(184 + uLM, 118 + uTM, cuxyz);
                        MainActivity.bdInfoData.text7.set(String.format("-%s.%s.%s", new String(ICM_data_To.year), new String(ICM_data_To.month), new String(ICM_data_To.day)));

//                                    sprintf(cuxyz, "%s.%s.%s-%s.%s.%s", PMU_data_From.year, PMU_data_From.month, PMU_data_From.day,
//                                            PMU_data_To.year, PMU_data_To.month, PMU_data_To.day);
//                                    outtextxy(120 + uLM, 136 + uTM, cuxyz);
                        MainActivity.bdInfoData.text8.set(String.format("%s.%s.%s-%s.%s.%s", new String(PMU_data_From.year), new String(PMU_data_From.month), new String(PMU_data_From.day),
                                new String(PMU_data_To.year), new String(PMU_data_To.month), new String(PMU_data_To.day)));

                    }
                }
                break;
//
            case SetFix_PRE:
//                            clearviewport();
//                            outtextxy(30, 15, "1.");
//                            che.puthz16(50, 20, 2, WHITE, "参考点坐标设定");
                changeStageUI(FragmentShuRuZuoBiaoV2.instance);

                MainActivity.cszb.input1.set("");
                MainActivity.cszb.input2.set("");
                MainActivity.cszb.input3.set("");

                if (FragmentShuRuZuoBiaoV2.instance.input1 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input1.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input2 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input2.setFocusableInTouchMode(true);
                }

                if (FragmentShuRuZuoBiaoV2.instance.input3 != null) {
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusable(true);
                    FragmentShuRuZuoBiaoV2.instance.input3.setFocusableInTouchMode(true);
                }
                FixFormat = FixGaussPlane;
                MainActivity.cszb.title.set("参考点坐标设定");
                MainActivity.cszb.row1_title.set("X=");
                MainActivity.cszb.row2_title.set("Y=");

                stage = SetFix_S1;
//
            case SetFix_S1:
//                            Clr_scr();
//                            che.puthz16(10, 5, 2, WHITE, "初");
//                            che.puthz16(10, 23, 2, WHITE, "始");
//                            che.puthz16(10, 41, 2, WHITE, "坐");
//                            che.puthz16(10, 59, 2, WHITE, "标");
//                            outtextxy(35, 6, "X=");
//                            outtextxy(35, 26, "Y=");
//                            outtextxy(35, 46, "H=");
                stage = SetFix_S2;
//
            case SetFix_S2:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();

                    if (keyEvent.type == Esc) {
                        stage = MENU_INI;
                    } else if (keyEvent.type == Enter) {
                        stage = SetFix_S3;
//                        dx = atol(data_buf[0]);
//                        dy = atol(data_buf[1]);
//                        lh = atoi(data_buf[2]);

                        String input1 = MainActivity.cszb.input1.get();
                        String input2 = MainActivity.cszb.input2.get();
                        String input3 = MainActivity.cszb.input3.get();
                        try {
                            dx = Long.parseLong(input1);
                            dy = Long.parseLong(input2);
                            lh = Short.parseShort(input3);
                        } catch (NumberFormatException e) {
                            MainActivity.alertNoReturn("坐标输入错误,请返回");
                            break;
                        }


                        if (dx < 0 || dx > 9000000 || dy < 0 || dy > 99999999 || lh < -100 || lh > 10000)            /*平面坐标输入错误*/ /*2010-6-6	10:04:03*/ {
                            stage = SetFix_S1;
                            MainActivity.alertNoReturn("坐标输入错误,请返回");
                            break;
                        }
                    }

                }
                break;
//
            case SetFix_S3:
//                            Clr_scr();
//                            che.puthz16(10, 5, 2, WHITE, "坐");
//                            che.puthz16(10, 23, 2, WHITE, "标");
//                            che.puthz16(10, 41, 2, WHITE, "确");
//                            che.puthz16(10, 59, 2, WHITE, "认");
//                            outtextxy(35, 6, "X=");
//                            outtextxy(35, 26, "Y=");
//                            outtextxy(35, 46, "H=");
//                            sprintf(cuxyz, "%ld", dx);
//                            sprintf(cuxyz, "%ld", dy);
//                            sprintf(cuxyz, "%d", lh);

                MainActivity.cszb.title.set("确认参考点坐标");
                MainActivity.cszb.input1.set(String.format(Locale.CHINA, "%d", dx));
                MainActivity.cszb.input2.set(String.format(Locale.CHINA, "%d", dy));
                MainActivity.cszb.input3.set(String.format(Locale.CHINA, "%d", lh));


                FragmentShuRuZuoBiaoV2.instance.input1.setFocusable(false);
                FragmentShuRuZuoBiaoV2.instance.input2.setFocusable(false);
                FragmentShuRuZuoBiaoV2.instance.input3.setFocusable(false);
                stage = SetFix_S4;
//
            case SetFix_S4:
                if (bioskey1()) {
                    KeyEvent keyEvent = bioskey0();
                    if (keyEvent.type == Esc) {
                        stage = SetFix_S1;
                    } else if (keyEvent.type == Enter) {
                        stage = MENU_INI;
                        buf[0] = (byte) 0xf2;
                        buf[1] = (byte) (dx & 0xff);
                        buf[2] = (byte) ((dx & 0xff00) >> 8);
                        buf[3] = (byte) ((dx & 0xff0000) >> 16);
                        buf[4] = (byte) (dy & 0xff);
                        buf[5] = (byte) ((dy & 0xff00) >> 8);
                        buf[6] = (byte) ((dy & 0xff0000) >> 16);
                        buf[7] = (byte) ((dy & 0xff000000L) >> 24);
                        if ((lh & 0x8000) > 0) {
                            lhr = (short) (lh & 0x7fff);
                            lhr -= 1;
                            buf[8] = (byte) (0xff & ~lhr);
                            buf[9] = (byte) ((0xff00 & ~lhr) >> 8);
                            buf[9] |= 0x80;
                        } else {
                            buf[8] = (byte) (lh & 0xff);
                            buf[9] = (byte) ((lh & 0xff00) >> 8);
                        }
                        Buf_Com3.PutData(buf, 16);
                    } else {
                    }
                }
                break;

            case SelfTest_PRE:
                buf[0] = (byte) 0xf0;
                Buf_Com3.PutData(buf, 8);
                postR = false;

//                            che.puthz16a(82, 8, 2, WHITE, "定位导航系统自检");
//                            che.puthz16a(10 + uLM, 5 + uTM, 2, WHITE, "方位保持仪");
//                            che.puthz16a(10 + uLM, 23 + uTM, 2, WHITE, "寻北仪");
//                            che.puthz16a(10 + uLM, 41 + uTM, 2, WHITE, "高程计");
//                            che.puthz16a(10 + uLM, 59 + uTM, 2, WHITE, "北斗用户机");
//                            che.puthz16a(10 + uLM, 77 + uTM, 2, WHITE, "显示控制器");
//                            che.puthz16a(10 + uLM, 95 + uTM, 2, WHITE, "导航显示器");
                changeStageUI(FragmentSelfTest.instance);

                stage = SelfTest_S1;

//
            case SelfTest_S1:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();

                    if (key.type == Key.Esc) {
                        stage = MENU_INI;
                    }
                } else if (timeFlag > 0) {
                    timeFlag = 0;
//                                if (!(++count % 36)) {
                    if (true) {
                        //DK:direction_keep
                        if ((ErrCodeFromBC & 0x0040) > 0
                                || (ErrCodeFromBC & 0x0002) > 0
                                || (ErrCodeFromBC & 0x0001) > 0
                                || (ErrCodeFromBC & 0x0004) > 0
                                || (ErrCodeFromBC & 0x0800) > 0
                                || (ErrCodeFromBC & 0x0400) > 0
                                || (ErrCodeFromBC & 0x0200) > 0
                                || (ErrCodeFromBC & 0x0100) > 0
                                || (ErrCodeFromBC & 0x2000) > 0
                                || (ErrCodeFromBC & 0x1000) > 0
                        ) {
//                                        che.puthz16a(198 + uLM, 5 + uTM, 2, WHITE, "故障");
                            MainActivity.selfTestData.text1.set("故障");
                            ErrCode |= 0x01;
                        } else {
//                                        che.puthz16a(198 + uLM, 5 + uTM, 2, WHITE, "正常");
                            MainActivity.selfTestData.text1.set("正常");

                            ErrCode &= 0xFE;
                        }
                        //NF	north_find
                        if ((ErrCodeFromBC & 0x0010) > 0) {
//                                        che.puthz16a(198 + uLM, 23 + uTM, 2, WHITE, "故障");
                            MainActivity.selfTestData.text2.set("故障");

//                            ErrCode |= 0x02;
                        } else {
                            MainActivity.selfTestData.text2.set("正常");
                        }
                        //BA	:高程计
                        if ((ErrCodeFromBC & 0x0008) > 0) {
                            MainActivity.selfTestData.text3.set("故障");

//                            ErrCode |= 0x08;
                        } else {
                            MainActivity.selfTestData.text3.set("正常");
//                                        che.puthz16a(198 + uLM, 41 + uTM, 2, WHITE, "正常");
                        }
                        //BD:Beidou
                        if (BD_Status == 0x0) {
                            MainActivity.selfTestData.text4.set("故障");
//                                        che.puthz16a(198 + uLM, 59 + uTM, 2, WHITE, "故障");
//                            ErrCode |= 0x40;
                        } else {
                            MainActivity.selfTestData.text4.set("正常");
//                                        che.puthz16a(198 + uLM, 59 + uTM, 2, WHITE, "正常");
                        }
                        //CDU: control display unit
//                                    che.puthz16a(198 + uLM, 77 + uTM, 2, WHITE, "正常");                //导航显示控制器不能用秒脉冲来表示了.
                        MainActivity.selfTestData.text5.set("正常");

                        //NDU: navigate	display	unit
                        if ((ErrCodeFromBC & 0x0080) > 0) {
                            MainActivity.selfTestData.text6.set("故障");
//                                        che.puthz16a(198 + uLM, 95 + uTM, 2, WHITE, "故障");
//								ErrCode|=0x10;
                        } else {
                            MainActivity.selfTestData.text6.set("正常");
//                                        che.puthz16a(198 + uLM, 95 + uTM, 2, WHITE, "正常");
                        }

                        stage = SelfTest_S2;
                    }
                }
                break;
//
            case SelfTest_S2:
                if (bioskey1()) {
                    KeyEvent key = bioskey0();

                    if (key.type == Key.Esc) {
                        stage = MENU_INI;
                    }
                }
                break;

            default:
                break;
        }            /*switch(stage)结束*/
//                    if (!(tim % 182) && (tim_token != tim)) {
        long seconds = TimeUnit.MILLISECONDS.toSeconds(tim() - tim_token);
        if (seconds > 10) {
            tim_token = tim();
            if (!NF_OnRun) {
                if (INS_Ini == 0 && seconds > 10) {
                    buf[0] = (byte) 0xf0;
                    Buf_Com3.PutData(buf, 8);
                } else {
                    ;
                }
                if (initG) {
                    buf[0] = (byte) 0xf1;
                    Buf_Com3.PutData(buf, 8);
                } else {
                    ;
                }
            }
        } else {
            ;
        }
///****************		 ******************/
        if (lotusFlag > 0) {
            lotusFlag = 0;
            tim_twin_a++;
            tim_twin_b++;
            if (!((tim_twin_b % 90) == 0)) {
                tim_twin_a -= 1;
            } else {
                tim_twin_b = tim_twin_a;
            }
            choke = false;
        }
//
///****************	 COM3	 *************/
        cn = Buf_Com3.InDataProc(bc_data);                                                            /*接受来自方位保持仪的数据*/
        if (cn > 0) {
            if (bc_data[0] == (byte) 0xfd)                                /*当保持收到命令字0x01,保持回idenBit[2]={0xFD,0x01};*/ {
                id_stat = bc_data[1];
                idReady = 1;
                if ((id_stat == (byte) 0xFF) && initG) {
//                                che.puthz16a(5, 236, 2, BLACK, "	方位保持仪复位 ");
                    MainActivity.alertNoReturn("方位保持仪复位");
                }
            } else if (bc_data[0] == (byte) 0xfe)                        /*自检结果,unsigned	char stResult[3]={0xFE,0,0};	*/ {
                if (NF_OnRun) {
                    bc_data[1] &= 0xEF;
                }
                if ((bc_data[2] & 0x08) == 0x08) {
                    if (fgTempCtrlAlarm) {
                        /*if	the	alarm	lasting	time less	then 300s, then	omitting it.*/
//                                    if ((tim - cntTempCtrlAlarm) < 5460) {  18.2是1s
                        if (TimeUnit.MILLISECONDS.toSeconds(tim() - cntTempCtrlAlarm) < 300) {
                            bc_data[2] = (byte) (bc_data[2] & 0xF7);
                        } else {
                            ;
                        }
                    } else {
                        bc_data[2] = (byte) (bc_data[2] & 0xF7);
                        fgTempCtrlAlarm = true;
                        cntTempCtrlAlarm = tim();
                    }
                } else {
                    if (fgTempCtrlAlarm) {
                        fgTempCtrlAlarm = false;
                    }
                }
//                            ErrCodeCur. byte[0]=bc_data[1];
//                            ErrCodeCur. byte[1]=bc_data[2];
                int ErrCodeCur = 0;
                ErrCodeCur = (bc_data[1]& 0xff);
                ErrCodeCur |= (bc_data[2]& 0xff) << 8;
                if (postR) {
                    if (ErrCodeFromBC == ErrCodeCur) {
                        ;
                    } else {
                        ErrCodeFromBC = ErrCodeCur;
                    }
                } else {
                    ErrCodeFromBC = ErrCodeCur;
                    postR = true;
                }
            } else if (bc_data[0] == (byte) 0xeb)                        /*测漂结束及状态 unsigned	char testD[2]={0xEB,0x00};	*/ {
                testDT = 1;
                if (!initG) initG = true;
            } else if (bc_data[0] == (byte) 0xec)                        /*寻北仪状态信息*/ {
                norFT = bc_data[1];
                buf[0] = (byte) 0xf0;
                Buf_Com3.PutData(buf, 8);
            } else if (bc_data[0] == (byte) 0xfc)                        /*方位保持仪导航数据,char	pd[16]={0xFC,}*/ {
//                ux1 = ((bc_data[1])) & 0xffffff;
                ux1 = 0;
                ux1 |= (bc_data[1] & 0xff);
                ux1 |=( bc_data[2]& 0xff) << 8;
                ux1 |= (bc_data[3]& 0xff) << 16;
//                uy1 = (bc_data[4]);
                uy1 = 0;
                uy1 |= (bc_data[4]& 0xff);
                uy1 |= (bc_data[5]& 0xff) << 8;
                uy1 |= (bc_data[6]& 0xff) << 16;
                uy1 |= (bc_data[7]& 0xff) << 24;


                DDrX54.setValue((double) ux1);
                DDrY54.setValue((double) uy1);
                iBelt = (int) floor(DDrY54.getValue() / 1e6);
                DDrY54.setValue(DDrY54.getValue() - iBelt * 1e6);
                DDrY54.setValue(DDrY54.getValue() - 5e5);
                rover.XY_BLCon(DDrX54.getValue(), DDrY54.getValue(), iBelt, DDrLat54, DDrLong54, DConvergence54, 0);
                if ((bc_data[9] & 0x80) > 0) {
                    uh1 = (short) (bc_data[8] & 0xff);
                    uh1 |= (bc_data[9]& 0xff) << 8;
                    uh1  &= 0x7fff;
                    uh1 = (short) (0x8000 - uh1);
                    uh1 |= 0x8000;
                } else {
//                    uh1 = ((bc_data[8])) & 0x7fff;
                    uh1 = (short) (bc_data[8]& 0xff);
                    uh1 |= (bc_data[9]& 0xff) << 8;
                    uh1  &= 0x7fff;

                }
                lar = (bc_data[10]) & 0xff;
                lar |= (bc_data[11]& 0xff) << 8 ;
                lar &= 0xffff;
                la = (float) (1.0 * lar / 10.);
                la = la - mountErr;

                if (la < 0) {
                    la = 6000 + la;
                } else if (la >= 6000) {
                    la = la - 6000;
                } else {
                    ;
                }
                ud = (bc_data[12]& 0xff);
                ud |= (bc_data[13]& 0xff) << 8;
                ud |= (bc_data[14]& 0xff) << 16;
                ud |= (bc_data[15]& 0xff) << 24;

                dDeltD = (double) ud - dStoredD;
                dStoredD = (double) ud;

            } else if (bc_data[0] == (byte) 0xfb)                        /*方位保持仪静态姿态角数据,int supp[8]={0xFB,0x0,0x0,0x0,0x0,0x0,0x0,0x0};*/ {
                short sint16 = (short) (bc_data[1]& 0xff);
                sint16 |= ((bc_data[2]& 0xff) << 8);
//                roll = -(double) ((((1.0 * bc_data[1]))) * 360 / 65536);        //车与寻北仪的pitch和roll相互交叉，且车抬头为正，左沉为正.
                roll = -((double) sint16) * 360 / 65536;
                sint16 = (short) (bc_data[3]& 0xff);
                sint16 |= ((bc_data[4]& 0xff) << 8);
//                pitch = -(double) (((1.0 * bc_data[3]))) * 360 / 65536;
                pitch = -((double) sint16) * 360 / 65536;

//                velocity = (double) (((1.0 * bc_data[5]))) / 36;                //10*3.6 unit:km/h->m/s
                sint16 = (short) (bc_data[5]& 0xff);
                sint16 |= (bc_data[6]& 0xff) << 8;
                velocity = ((double) sint16) / 36;

            } else if (bc_data[0] == (byte) 0xca)                        /*标定结束命令字，在保持XL2002.CPP中void calibration()*/ {
                calOk = 1;
            } else if (bc_data[0] == (byte) 0xe7)                                        /*当保持受到命令字为0xe4(backdoor),*/ {
//                lar = ((bc_data[1])) & 0xffff;        //方位保持传来的里程系数
                lar = bc_data[1] & 0xff;
                lar |= (bc_data[2]& 0xff) << 8;
                lar &= 0xffff;
                k = (double) lar / 1e4;                                        //显控里的里程系数已经除以10000
//                lhr = (short) (((bc_data[3])) & 0xffff);        //方位保持传来的安装误差
                lhr = (short) (bc_data[3] & 0xff);
                lhr |=  (bc_data[4]& 0xff) << 8;
                lhr &= 0xffff;
                mntErr = (double) lhr / 10.;                                //显控里的安装误差已经除以10
            } else if (bc_data[0] == (byte) 0xaa)                                        /*接受方位保持仪的ACK包*/ {
            } else {
            }
        }
        cn = Buf_Com3.ReadOutBuf(obuf);

        if (cn > 0)                                                                                                                /*往方位保持仪发送数据*/ {
            send_string_com(COM3, cn, obuf);
        }

///****************	 COM1	 *************/
        cn = Buf_Com1.GetData(zc_data);                                                                    /*读来自通信处理机的命令*/
        if (cn > 0) {
            zc_data[cn] = 0x0D;
            zc_data[cn + 1] = 0x0A;
            cn = cn + 2;
            send_string_com(COM4, cn, zc_data);                                                        /*往北斗发送来自通信处理机的命令*/
//                        send_string_com(COM2, cn, zc_data);                                                        /*往串口2发送来自通信处理机的命令*/
        }

//        if ((!(tim_twin_a % 9 > 0)) && (!choke) && (tim_twin_c != tim_twin_a)) {                                                                       /*0.5s周期,非数据发送过程中,往通信处理发送惯导数据*/
        if (seconds >= 1 && !choke) {                                                                       /*0.5s周期,非数据发送过程中,往通信处理发送惯导数据*/
            {
                tim_twin_c = tim_twin_a;
                choke = true;
//                        Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "$INDWX,");
                toZC_DATA += sprintf("$INDWX,");
                if (initG)                                                                        /*惯导已启动*/ {
                    if ((ErrCodeFromBC & 0x0080) > 0) {                                   /*导航显示器故障*/

//                                Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "2,");                            /*降级使用*/
                        toZC_DATA += sprintf("2,");
                    } else {
//                                Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                            /*正常使用*/
                        toZC_DATA += sprintf("1,");

                    }
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                                /*当前数据有效*/
                    toZC_DATA += sprintf("1,");

                    if (GGA_Data_Status > 0)                                                    /*卫星数据状态指示非零*/
//                                Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "2,");                        /*定位数据来源：融合*/
                        toZC_DATA += sprintf("2,");

                    else
//                                Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                        /*定位数据来源：惯性*/
                        toZC_DATA += sprintf("0,");

                    if ((stage == ALIGN_S1) || (stage == DRIFT_CAL))    /*在寻北或测漂过程中*/ {
//                                Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                        /*定位数据记忆*/
//                                Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                        /*定向数据记忆*/
                        toZC_DATA += sprintf("1,");
                        toZC_DATA += sprintf("1,");

                    } else {
//                                Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                        /*定位数据刷新*/
//                                Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");
                        toZC_DATA += sprintf("0,");
                        toZC_DATA += sprintf("0,");
                        /*定向数据刷新*/
                    }
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%.3f,", (la * 0.06));                /*航向，°*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%.2f,", velocity);                    /*速度，m/s*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%.2f,", pitch);                        /*俯仰角，°*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%.2f,", roll);                            /*俯仰角，°*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%d,", uh1);                                /*高度，m*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%lu,", ux1);                                /*位置X,m*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%lu,", uy1);
                    toZC_DATA += sprintf("%.3f,", (la * 0.06));                /*航向，°*/
                    toZC_DATA += sprintf("%.2f,", velocity);                    /*速度，m/s*/
                    toZC_DATA += sprintf("%.2f,", pitch);                        /*俯仰角，°*/
                    toZC_DATA += sprintf("%.2f,", roll);                            /*俯仰角，°*/
                    toZC_DATA += sprintf("%d,", uh1);                                /*高度，m*/
                    toZC_DATA += sprintf("%d,", ux1);                                /*位置X,m*/
                    toZC_DATA += sprintf("%d,", uy1);                                /*位置Y,m*/
                } else                                                                                /*惯导没有启动*/ {
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "2,");                                /*降级使用*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                                /*当前数据无效*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                                /*定位数据来源：卫星*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                                /*定位数据刷新*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                                /*定向数据记忆*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%.3f,", (la * 0.06));
                    toZC_DATA += sprintf("2,");                                /*降级使用*/
                    toZC_DATA += sprintf("0,");                                /*当前数据无效*/
                    toZC_DATA += sprintf("0,");                                /*定位数据来源：卫星*/
                    toZC_DATA += sprintf("0,");                                /*定位数据刷新*/
                    toZC_DATA += sprintf("1,");                                /*定向数据记忆*/
                    toZC_DATA += sprintf("%.3f,", (la * 0.06));                /*航向，°*/
////					Len_toZC_DATA+=sprintf(toZC_DATA+Len_toZC_DATA,",");												/*航向，空字符*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, ",");                                                /*速度，空字符*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%.2f,", pitch);                        /*俯仰角，°*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%.2f,", roll);                            /*俯仰角，°*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%d,", BdHeight);                        /*高度，m*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%lu,", BdX);                                /*位置X,m*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "%lu,", BdY);                                /*位置Y,m*/
                    toZC_DATA += sprintf(",");                                                /*速度，空字符*/
                    toZC_DATA += sprintf("%.2f,", pitch);                        /*俯仰角，°*/
                    toZC_DATA += sprintf("%.2f,", roll);                            /*俯仰角，°*/
                    toZC_DATA += sprintf("%d,", BdHeight);                        /*高度，m*/
                    toZC_DATA += sprintf("%d,", BdX);                                /*位置X,m*/
                    toZC_DATA += sprintf("%d,", BdY);                                /*位置Y,m*/

                }

//                        if ((ErrCode & 0x01)  > 0)                                                   /*方位保持仪故障*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                            /*故障*/
//                        else
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                            /*正常*/
//                        if ((ErrCodeFromBC & 0x0010)   > 0)                                  /*寻北仪故障*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                            /*故障*/
//                        else
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                            /*正常*/
//                        if ((ErrCodeFromBC & 0x0008)       > 0)                              /*高程计故障*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                            /*故障*/
//                        else
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                            /*正常*/
//                        if ((ErrCodeFromBC & 0x0080)    >0)                                /*导航显示器故障*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1,");                            /*故障*/
//                        else
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0,");                            /*正常*/
//                        /*显示控制器故障*/
//                        Len_toZC_DATA += sprintf(toZC_DATA + toZC_DATA, "0,");                            /*正常*/
//
//                        if (BD_Status == 0x0)                                                /*北斗用户机故障*/
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "1");                            /*故障*/
//                        else
//                            Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "0");                            /*正常*/
//
                if ((ErrCode & 0x01) > 0)                                                   /*方位保持仪故障*/
                    toZC_DATA += sprintf("1,");                            /*故障*/
                else
                    toZC_DATA += sprintf("0,");                            /*正常*/
                if ((ErrCodeFromBC & 0x0010) > 0)                                  /*寻北仪故障*/
                    toZC_DATA += sprintf("1,");                            /*故障*/
                else
                    toZC_DATA += sprintf("0,");                            /*正常*/
                if ((ErrCodeFromBC & 0x0008) > 0)                              /*高程计故障*/
                    toZC_DATA += sprintf("1,");                            /*故障*/
                else
                    toZC_DATA += sprintf("0,");                            /*正常*/
                if ((ErrCodeFromBC & 0x0080) > 0)                                /*导航显示器故障*/
                    toZC_DATA += sprintf("1,");                            /*故障*/
                else
                    toZC_DATA += sprintf("0,");                            /*正常*/
                /*显示控制器故障*/
                toZC_DATA += sprintf("0,");                            /*正常*/

                if (BD_Status == 0x0)                                                /*北斗用户机故障*/
                    toZC_DATA += sprintf("1");                            /*故障*/
                else
                    toZC_DATA += sprintf("0");                            /*正常*/
                /*接受到北斗数据为正常,10秒内接受不到数据为故障*/
                checksum = 0;
//                        for (int i = 1; i < Len_toZC_DATA; i++) {
//                            checksum ^= toZC_DATA[i];
//                        }
                for (int i = 1; i < toZC_DATA.length(); i++) {
                    checksum ^= toZC_DATA.charAt(i);
                }
                checksum = checksum & 0xff;                    //将16进制的高4位和低4位转换成两个ASCII字符，（0-9，A-F）。最高有效位首先发送。
                checksum_L = checksum & 0x0f;
                checksum_H = (checksum >> 4) & 0x0f;
                if (checksum_L <= 9)
                    checksum_L = checksum_L + 0x30;
                else
                    checksum_L = checksum_L + 0x37;
                if (checksum_H <= 9)
                    checksum_H = checksum_H + 0x30;
                else
                    checksum_H = checksum_H + 0x37;
//                        Len_toZC_DATA += sprintf(toZC_DATA + Len_toZC_DATA, "*%c%c%c%c", checksum_H, checksum_L, 0x0D, 0x0A);
                toZC_DATA += sprintf("*%c%c%c%c", checksum_H, checksum_L, 0x0D, 0x0A);
                Len_toZC_DATA = toZC_DATA.length();
                send_string_com(Buf_Com1, Len_toZC_DATA, toZC_DATA.getBytes());
                Len_toZC_DATA = 0;
                toZC_DATA = "";
                choke = false;
            }
        }
///****************	 COM4	 *************/
        cn = Buf_Com4.GetData(bd_data_x);
        if (cn > 0)                                                                                                                /*收到北斗串口数据,判断是否GGA或DWR定位数据*/ {
            bd_data_x[cn] = 0x0D;
            bd_data_x[cn + 1] = 0x0A;
            cn = cn + 2;
            send_string_com(COM1, cn, bd_data_x);                                                    /*往上位机发送来自北斗的数据*/
            BDchBox = new byte[32][32];
//                        send_string_com(COM2, cn, bd_data_x);                                                    /*往串口2发送来自北斗的数据*/
            if (bd_data_x[3] == 'D' && bd_data_x[4] == 'W' && bd_data_x[5] == 'R' && bd_data_x[7] == '1')                /*RDSS定位反馈语句,*/ {                                                                                                                                                            /*并且是本用户设备进行定位申请返回的定位信息*/
                Num_DWR++;                                                                                                                                    /*RDSS定位次数*/
                if (Num_DWR > 65534)
                    Num_DWR = 1;                                                                                                /*防止DWR次数为负数*/
                BDchRow = 0;
                BDchFile = 0;
                for (int i = 0; ; i++) {
                    if (bd_data_x[i] == '*') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        break;
                    } else if (bd_data_x[i] == 0x0A && bd_data_x[i - 1] == 0x0D) {
                        break;
                    } else if (bd_data_x[i] == ',') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        BDchRow++;
                        BDchFile = 0;
                        continue;
                    } else {
                        BDchBox[BDchRow][BDchFile++] = bd_data_x[i];
                    }
                }
                if (BDchBox[3][0] == '\0')                                                                                                        //定时信息字段为空时
                {
                    ;
                } else {
                    byte[] temp_time = new byte[]{0, 0, '\0'};
                    temp_time[0] = BDchBox[3][0];
                    temp_time[1] = BDchBox[3][1];
                    RDSS_BeiDouTime.ti_hour = atoi(temp_time);
                    temp_time[0] = BDchBox[3][2];
                    temp_time[1] = BDchBox[3][3];
                    RDSS_BeiDouTime.ti_min = atoi(temp_time);
                    temp_time[0] = BDchBox[3][4];
                    temp_time[1] = BDchBox[3][5];
                    RDSS_BeiDouTime.ti_sec = atoi(temp_time);
                }
                if (BDchBox[4][0] == '\0')                                                                                                        //纬度信息字段为空时
                {
                    ;
                } else {
                    RDSS_BdLatitude = (double) ((BDchBox[4][0] & 0x0F) * 10 + (BDchBox[4][1] & 0x0F));
                    BDchBox[4][0] = '0';
                    BDchBox[4][1] = '0';
                    RDSS_BdLatitude = RDSS_BdLatitude + atof(BDchBox[4]) / 60;                                                                                        //单位为度
                }
                RDSS_BdLatitude_Dir = BDchBox[5][0];                                                                                //纬度方向
                if (BDchBox[6][0] == '\0')                                                                                                        //经度信息字段为空时
                {
                    ;
                } else {
                    RDSS_BdLongitude = (double) ((BDchBox[6][0] & 0x0F) * 100 + (BDchBox[6][1] & 0x0F) * 10 + (BDchBox[6][2] & 0x0F));
                    BDchBox[6][0] = '0';
                    BDchBox[6][1] = '0';
                    BDchBox[6][2] = '0';
                    RDSS_BdLongitude = RDSS_BdLongitude + atof(BDchBox[6]) / 60;                                                                                    //单位为度
                }
                RDSS_BdLongitude_Dir = BDchBox[7][0];                                                                                //经度方向
                RDSS_BdHeight = atoi(BDchBox[8]);                                                                                        //天线大地高,单位为米(2.1协议定),但炮研所要求750厂和54所更改成海拔高
                RDSS_BdVarHeight = atoi(BDchBox[10]);                                                                                //高程异常值,单位为米
                iBelt = (int) ((RDSS_BdLongitude / 6) + 1);
                rover.Bl_XY(RDSS_BdLatitude * M_PI / 180., (RDSS_BdLongitude - (6 * iBelt - 3)) * M_PI / 180., BdX_double, BdY_double, 2);                //参数'2'表示CGCS2000坐标
                RDSS_BdX.setValue(BdX_double.getValue().intValue());
                RDSS_BdY.setValue((int) (BdY_double.getValue() + 5e5 + iBelt * 1e6));

            }
            if (bd_data_x[3] == 'G' && bd_data_x[4] == 'G' && bd_data_x[5] == 'A') {
                BDchRow = 0;
                BDchFile = 0;
                for (int i = 0; ; i++) {
                    if (bd_data_x[i] == '*') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        break;
                    } else if (bd_data_x[i] == 0x0A && bd_data_x[i - 1] == 0x0D) {
                        break;
                    } else if (bd_data_x[i] == ',') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        BDchRow++;
                        BDchFile = 0;
                        continue;
                    } else {
                        BDchBox[BDchRow][BDchFile++] = bd_data_x[i];
                    }
                }
                if (BDchBox[6][0] == '0')                                                                                                                    //0-定位模式不可用或无效
                {
                    GGA_Data_Status = 0;
                    BeiDouTime.ti_hour = 0;
                    BeiDouTime.ti_min = 0;
                    BeiDouTime.ti_sec = 0;
                    BdLatitude = 0;
                    BdLongitude = 0;
                    BdHeight = 0;
                    BdVarHeight = 0;
                } else {
                    if (BDchBox[1][0] == '\0')                                                                                                        //定时信息字段为空时
                    {
                        BeiDouTime.ti_hour = 0;
                        BeiDouTime.ti_min = 0;
                        BeiDouTime.ti_sec = 0;
                    } else {
                        byte temp_time[] = new byte[]{0, 0, '\0'};
                        temp_time[0] = BDchBox[1][0];
                        temp_time[1] = BDchBox[1][1];
                        BeiDouTime.ti_hour = atoi(temp_time);
                        temp_time[0] = BDchBox[1][2];
                        temp_time[1] = BDchBox[1][3];
                        BeiDouTime.ti_min = atoi(temp_time);
                        temp_time[0] = BDchBox[1][4];
                        temp_time[1] = BDchBox[1][5];
                        BeiDouTime.ti_sec = atoi(temp_time);
                    }
                    if (BDchBox[2][0] == '\0')                                                                                                        //定位信息字段为空时
                    {
                        BdLatitude = 0;
                    } else {
                        BdLatitude = (double) ((BDchBox[2][0] & 0x0F) * 10 + (BDchBox[2][1] & 0x0F));
                        BDchBox[2][0] = '0';
                        BDchBox[2][1] = '0';
                        BdLatitude = BdLatitude + atof(BDchBox[2]) / 60;                                                        //单位为度
                    }
                    BdLatitude_Dir = BDchBox[3][0];                                                                                            //纬度方向
                    if (BDchBox[4][0] == '\0')                                                                                                        //定位信息字段为空时
                    {
                        BdLongitude = 0;
                    } else {
                        BdLongitude = (double) ((BDchBox[4][0] & 0x0F) * 100 + (BDchBox[4][1] & 0x0F) * 10 + (BDchBox[4][2] & 0x0F));
                        BDchBox[4][0] = '0';
                        BDchBox[4][1] = '0';
                        BDchBox[4][2] = '0';
                        BdLongitude = BdLongitude + atof(BDchBox[4]) / 60;                                                                                    //单位为度
                    }
                    BdLongitude_Dir = BDchBox[5][0];                                                                                        //经度方向
                    GGA_Data_Status = atoi(BDchBox[6]);                                                                                    //状态指示,0-8
                    Num_Statelite = atoi(BDchBox[7]);                                                                                        //可视卫星数
                    HDOP = atof(BDchBox[8]);                                                                                                        //HDOP值,	水平精度因子
                    BdHeight = atoi(BDchBox[9]);                                                                                                //天线大地高,单位为米(2.1协议定),但炮研所要求750厂和54所更改成海拔高
                    BdVarHeight = atoi(BDchBox[11]);                                                                                        //高程异常值,单位为米
                    VDOP = atof(BDchBox[15]);                                                                                                        //VDOP值,垂直精度因子
                    iBelt = (int) ((BdLongitude / 6) + 1);
                    rover.Bl_XY(BdLatitude * M_PI / 180., (BdLongitude - (6 * iBelt - 3)) * M_PI / 180., BdX_double,
                            BdY_double, 2);                //参数'2'表示CGCS2000坐标
                    BdX = (int) BdX_double.getValue().intValue();
                    BdY = (int) (BdY_double.getValue() + 5e5 + iBelt * 1e6);
                    //todo
                    RCV_FRM_BDGGA_tim = tim();                                        //收到北斗串口GGA数据内部时刻
                }
            }
            if (bd_data_x[3] == 'P' && bd_data_x[4] == 'M' && bd_data_x[5] == 'U')                                            //20161121 增加PMU读取
            {
                send_string_com(COM4, 20, PMU_CLOSE);                    //关闭精测码PMU有效期查询
                BDchRow = 0;
                BDchFile = 0;
                for (int i = 0; ; i++) {
                    if (bd_data_x[i] == '*') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        break;
                    } else if (bd_data_x[i] == 0x0A && bd_data_x[i - 1] == 0x0D) {
                        break;
                    } else if (bd_data_x[i] == ',') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        BDchRow++;
                        BDchFile = 0;
                        continue;
                    } else {
                        BDchBox[BDchRow][BDchFile++] = bd_data_x[i];
                    }
                }
                if (BDchBox[1][0] == '0')                                                                                                                    //没有频点 2016.11.21
                {
                } else if (BDchBox[1][0] == '1')                                                                                                            //频点1 2016.11.21
                {
                } else if (BDchBox[1][0] == '2')                                                                                                            //频点2 2016.11.21
                {
                } else if (BDchBox[1][0] == '3')                                                                                                        //频点3 2016.11.21
                {                                                                                                                                                            //功能有B3单频、B1/B3双频定位，都有B3，所以只显B3的PRM时效。
                    PMU_data_From.FP[0] = BDchBox[1][0];

                    PMU_data_From.day[0] = BDchBox[2][0];
                    PMU_data_From.day[1] = BDchBox[2][1];
                    PMU_data_From.month[0] = BDchBox[2][2];
                    PMU_data_From.month[1] = BDchBox[2][3];
                    PMU_data_From.year[0] = BDchBox[2][4];
                    PMU_data_From.year[1] = BDchBox[2][5];

                    PMU_data_To.day[0] = BDchBox[3][0];
                    PMU_data_To.day[1] = BDchBox[3][1];
                    PMU_data_To.month[0] = BDchBox[3][2];
                    PMU_data_To.month[1] = BDchBox[3][3];
                    PMU_data_To.year[0] = BDchBox[3][4];
                    PMU_data_To.year[1] = BDchBox[3][5];
                } else {

                }
            }
            if (bd_data_x[3] == 'I' && bd_data_x[4] == 'C' && bd_data_x[5] == 'M') {
                send_string_com(COM4, 20, ICM_CLOSE);                    //关闭密钥ICM终止期查询
                BDchRow = 0;
                BDchFile = 0;
                for (int i = 0; ; i++) {
                    if (bd_data_x[i] == '*') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        break;
                    } else if (bd_data_x[i] == 0x0A && bd_data_x[i - 1] == 0x0D) {
                        break;
                    } else if (bd_data_x[i] == ',') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        BDchRow++;
                        BDchFile = 0;
                        continue;
                    } else {
                        BDchBox[BDchRow][BDchFile++] = bd_data_x[i];
                    }
                }
                ICM_data_To.day[0] = BDchBox[1][0];
                ICM_data_To.day[1] = BDchBox[1][1];
                ICM_data_To.month[0] = BDchBox[1][2];
                ICM_data_To.month[1] = BDchBox[1][3];
                ICM_data_To.year[0] = BDchBox[1][4];
                ICM_data_To.year[1] = BDchBox[1][5];
            }
            if (bd_data_x[3] == 'Z' && bd_data_x[4] == 'D' && bd_data_x[5] == 'A') {
                BDchRow = 0;
                BDchFile = 0;
                for (int i = 0; ; i++) {
                    if (bd_data_x[i] == '*') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        break;
                    } else if (bd_data_x[i] == 0x0A && bd_data_x[i - 1] == 0x0D) {
                        break;
                    } else if (bd_data_x[i] == ',') {
                        BDchBox[BDchRow][BDchFile++] = '\0';
                        BDchRow++;
                        BDchFile = 0;
                        continue;
                    } else {
                        BDchBox[BDchRow][BDchFile++] = bd_data_x[i];
                    }
                }
                if (BDchBox[3][0] == '\0')                                                                                                        //日
                {
                    ;
                } else {
                    BDZH_data.day[0] = BDchBox[3][0];
                    BDZH_data.day[1] = BDchBox[3][1];
                }
                if (BDchBox[4][0] == '\0')                                                                                                        //月
                {
                    ;
                } else {
                    BDZH_data.month[0] = BDchBox[4][0];
                    BDZH_data.month[1] = BDchBox[4][1];
                }
                if (BDchBox[5][0] == '\0')                                                                                                        //年
                {
                    ;
                } else {
                    BDZH_data.year[0] = BDchBox[5][0];
                    BDZH_data.year[1] = BDchBox[5][1];
                    BDZH_data.year[2] = BDchBox[5][2];
                    BDZH_data.year[3] = BDchBox[5][3];
                }
            }
            if (bd_data_x[3] == 'F' && bd_data_x[4] == 'K' && bd_data_x[5] == 'I' && bd_data_x[7] == 'Z' && bd_data_x[8] == 'H' && bd_data_x[9] == 'S')    //自毁反馈语句
            {
                if (bd_data_x[11] == 'Y')                                    //$BDFKI,ZHS,Y,Y,0,0000*1F,指令执行成功.
                    FKI_ZHS = 'Y';
                else if (bd_data_x[11] == 'N')                        //$BDFKI,ZHS,Y,Y,0,0000*1F,指令执行失败.
                    FKI_ZHS = 'N';
                else
                    FKI_ZHS = 0;

                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = sdf.format(date);
                String text = String.format("Response received once at %s, data is [%c] \n", currentTime, FKI_ZHS);
                writeBDZH(text);
//todo
//                            fp_BDZH = fopen("BDZH.txt", "a+t");            //接收到自毁反馈语句后往文件记录时间
//                            if (fp_BDZH) {
//                                fseek(fp_BDZH, 0, SEEK_END);
//                                fprintf(fp_BDZH, "Response received once at %s.%s.%s \n", BDZH_data.year, BDZH_data.month, BDZH_data.day);
//                            }
//                            fclose(fp_BDZH);
            }

//
            RCV_FRM_BD_tim = tim();                                                                //收到北斗串口数据内部时刻
            BD_Status = 1;                                                                            //接受到北斗串口数据后,北斗状态设置为正常.
        }
        if (TimeUnit.MILLISECONDS.toSeconds(tim() - RCV_FRM_BD_tim) >= 10)                                     //如果收不到北斗串口数据超过约10秒,则北斗故障状态设成故障
        {
            BD_Status = 0;
        }
//
//                    if ((tim - RCV_FRM_BDGGA_tim) >= 182)                                    //如果收不到北斗数据超过约10秒,则数据有效状态及北斗状态设成无效,
        if (TimeUnit.MILLISECONDS.toSeconds(tim() - RCV_FRM_BDGGA_tim) >= 10)                                     //如果收不到北斗串口数据超过约10秒,则北斗故障状态设成故障

        {                                                                                                    //数据置零或使用RDSS值,清标记
            GGA_Data_Status = 0;
            Num_Statelite = 0;
            HDOP = 0;
            VDOP = 0;
            BDchBox[0][1] = 0;
            BDchBox[0][2] = 0;
            if (Num_DWR > 0) {
                BeiDouTime.ti_hour = RDSS_BeiDouTime.ti_hour;
                BeiDouTime.ti_min = RDSS_BeiDouTime.ti_min;
                BeiDouTime.ti_sec = RDSS_BeiDouTime.ti_sec;
                BdLatitude = RDSS_BdLatitude;
                BdLongitude = RDSS_BdLongitude;
                BdHeight = RDSS_BdHeight;
                BdVarHeight = RDSS_BdVarHeight;
                BdX = RDSS_BdX.getValue().intValue();
                BdY = RDSS_BdY.getValue().intValue();
            } else {
                BeiDouTime.ti_hour = 0;
                BeiDouTime.ti_min = 0;
                BeiDouTime.ti_sec = 0;
                BdLatitude = 0;
                BdLongitude = 0;
                BdHeight = 0;
                BdVarHeight = 0;
                BdX = 0;
                BdY = 0;
            }
        }
//            }            /*while	大循环结束*/
//
////******************************************************
//            cleardevice();
//            ccc.program_end();
//
        if(STOP) {

            buf[0] = 0x77;
            Buf_Com3.PutData(buf, 8);
            cn = Buf_Com3.ReadOutBuf(obuf);
            if (cn > 0) {
                send_string_com(COM3, cn, obuf);
            }
//            quitSys();
        }


    }        /*主函数结束*/

    private static void writeBDZH(String text) {
        try {
            checkPermission();
            String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
            FileWriter writer = new FileWriter(absolutePath + "/BDZH.txt", true);
            BufferedWriter bufferedWriter = new BufferedWriter(writer);

            bufferedWriter.write(text);
            bufferedWriter.close();
        } catch (IOException e) {
//                            throw new RuntimeException(e);
            Log.e("bdzh write", "bdzh write error ", e);
        }
    }

    static void  checkPermission() {
        MainActivity instance = MainActivity.instance;
        String writeExternalStorage = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if (ContextCompat.checkSelfPermission(instance, writeExternalStorage)
                != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(instance,
                    writeExternalStorage)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed; request the permission
                ActivityCompat.requestPermissions(instance,
                        new String[]{writeExternalStorage},
                        0);

                // MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }
    private static void send_string_com(serbuf bufCom, int len, byte[] out) {
        if (bufCom instanceof COM1_Buf) {
            MainActivity.spManager.send(MainActivity.COM1_PORT, Arrays.copyOf(out, len));
        }
        if (bufCom instanceof COM3_Buf) {
            // 串口有问题，现在不需要了
            MainActivity.spManager.send(MainActivity.COM3_PORT, Arrays.copyOf(out, len));
        }
        if (bufCom instanceof COM4_Buf) {
            MainActivity.spManager.send(MainActivity.COM4_PORT, Arrays.copyOf(out, len));
        }
    }

    private static String sprintf(String fmt, Object... arg) {
        return String.format(Locale.CHINA, fmt, arg);
    }


    private static void changeStageUI(Fragment f) {
        MainActivity.fragmentManager.beginTransaction().replace(R.id.contentFrame, f).commit();
    }

    //
//        /*函数定义*/
////    void interrupt My_timer(__CPPARGS)
////    {
////        tim++;																			//内部定时器中断次数计数
////        timeFlag=1;																	//定时器中断标志
////        lotusFlag=1;																//定时器中断标志,用于调整5秒整90次计数整数.
////        Old_IRQ0(__CPPARGS);
////    }
//        /*函数定义*/
//        void interrupt_My_timer ()
//        {
//            tim++;                                                                            //内部定时器中断次数计数
//            timeFlag = 1;                                                                    //定时器中断标志
//            lotusFlag = 1;                                                                //定时器中断标志,用于调整5秒整90次计数整数.
//        }
//
    static void initSys() {
//            fp = fopen("data8.dat", "rb");
//            if (!fp) {
//            } else {
//                fseek(fp, 0 * sizeof( float),0);
//                fread( & mountErr, 4, 1, fp);                //First	4	bytes	for	defaultErr
//                fclose(fp);
//            }
//            initial_com_port(COM1);
////	initial_com_port(COM2);
//            init_com(COM3);
//            init_com(COM4);
//            init_int();
//
//            Old_IRQ0 = getvect(0x08);
//
//            disable();
//            setvect(0x08, My_timer);
//            enable();
        buf[0] = (byte) 0xe4;
        Buf_Com3.PutData(buf, 8);
//
//            clrscr();
        return;
    }

    static float atof(byte[] a) {
        try {
            return Float.parseFloat("" + new String(a));
        } catch (Exception e) {
            Log.e("atof", "atof: ", e);
            return 0.0F;
        }
    }

    static int atoi(byte[] a) {
        try {
            return Float.valueOf("" + new String(a)).intValue();
        } catch (NumberFormatException e) {
            Log.e("atoi", "atoi: ", e);
            return 0;
        } catch (Exception e) {
            Log.e("atoi", "atoi: ", e);
            return 0;
        }
    }

    static boolean bioskey1() {
        return keyQueue.size() > 0;
    }

    static KeyEvent bioskey0() {
        return keyQueue.poll();
    }

}

class BeidouTime {
    int ti_hour;
    int ti_min;
    int ti_sec;
}

